(BFS+回溯)迷宫问题 POJ3984
题目内容
定义一个二维数组:
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题,但是因为要输出它的路径,所以稍有些复杂。
我们可以用一个变量来记录这个点的上一个点的下标,最后只要递归输出就好。
代码
#include<iostream>
using namespace std;
int maze[10][10],way[4][2]={{1,0},{-1,0},{0,1},{0,-1}},vis[10][10]={0};
int top=0,tail=0;
struct que
{
int x,y;
int p;//记录上一个点
}q[100];
void bfs()
{
int i;
que temp;
q[0].x=0;
q[0].y=0;
q[0].p=-1;//用-1标志起始位置
tail++;
vis[0][0]=1;
while(top<tail)
{
for(i=0;i<=3;i++)
{
temp.x=q[top].x+way[i][0];
temp.y=q[top].y+way[i][1];
if(temp.x>=0 && temp.x<5 && temp.y>=0 && temp.y<5 && maze[temp.x][temp.y]!=1 && vis[temp.x][temp.y]==0)
{
q[tail].x=temp.x;
q[tail].y=temp.y;
q[tail].p=top;
tail++;
vis[temp.x][temp.y]=1;
if(temp.x==4 && temp.y==4)
return;
}
}
top++;
}
}
void print(que pre)
{
if(pre.p==-1)
{
cout<<"("<<pre.x<<", "<<pre.y<<")"<<endl;
}
else
{
print(q[pre.p]);//递归输出
cout<<"("<<pre.x<<", "<<pre.y<<")"<<endl;
}
return;
}
int main()
{
int i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
cin>>maze[i][j];
bfs();
print(q[tail-1]);
return 0;
}