版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
思路
寻找路径很简单,最基本的bfs的题目,而这道题还涉及到路径记录,这里使用的方法和并查集中的parent数组的思路相似,也是用一个Root数组记录每个点的父节点,然后输出的时候直接递归倒序输出就vans了。
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
int _map[5][5];
bool vis[5][5];
int dic[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct point
{
int x,y,root;
};
point ans[25];
bool judge(int _x,int _y)
{
return _x>=0&&_x<5&&_y>=0&&_y<5;
}
void print(point p)
{
while(p.root!=-1)
{
print(ans[p.root]);
cout<<"("<<p.x<<", "<<p.y<<")\n";
return;
}
cout<<"(0, 0)\n";
}
void bfs(int x,int y)
{
point p;
p.x=x;
p.y=y;
queue<point> num;
num.push(p);
int cnt=0,k=0;
p.root=-1;
ans[0]=p;
cnt++;
while(!num.empty())
{
point q=num.front();
num.pop();
if(p.x==4&&p.y==4)
{
print(p);
return;
}
for(int i=0; i<4; i++)
{
int _x=q.x+dic[i][0];
int _y=q.y+dic[i][1];
if(!vis[_x][_y]&&!_map[_x][_y]&&judge(_x,_y))
{
vis[_x][_y]=true;
p.x=_x,p.y=_y;
p.root=k;
num.push(p);
ans[cnt++]=p;
}
}
k++;
}
}
int main()
{
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
vis[i][j]=false;
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
cin>>_map[i][j];
bfs(0,0);
}