题目:一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
要求打印最短路线坐标,可以套用bfs模板做的简单题,很适合用来学习bfs,可以自己手动debug一下来体会bfs。
其中比较难理解的就是pre[]数组了,可以看做是一个数组模拟的树状结构,用来记录bfs过程中每一次中,上一步和下一步的联系。
以这个为例
上一行是最短路线坐标,下一行是pre数组中存的数,0->(1,0),1->(2,0)依次类推,理论上3->(3,0)但我们不需要那条路。
打印的时候用了一个递归,像栈一样,从里往外打印。
因为head此时等于17
pre[17]=14 ->pre[14]=11->pre[11]=8………
一直推到pre[1]=0为止。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[5][5],vis[5][5],pre[30];//分别代表迷宫,是否走过,走的路线
int p[] = {0,1,0,-1},q[] = {1,0,-1,0};
struct cam
{
int x;
int y;
} lis[30]; //记录走过的坐标
void print(int x)
{
int t;
t=pre[x];
if(t==0)
{
printf("(0, 0)\n");
printf("(%d, %d)\n",lis[x].x,lis[x].y);
return;
}
else
print(t);
printf("(%d, %d)\n",lis[x].x,lis[x].y);
return;
}
void bfs()
{
int head,tail;
int x,y,tx,ty;
head = 0;
tail = 1;
lis[0].x = 0;
lis[0].y = 0;
pre[0] = -1;
while(head < tail)
{
x = lis[head].x;
y = lis[head].y;
if(x==4 && y==4)
{
print(head);
return;
}
for(int i=0; i<4; i++)
{
tx = x+p[i];
ty = y+q[i];
if(tx<0 || tx>4 || ty<0 || ty>4 || a[tx][ty]==1)
continue;
if(!vis[tx][ty])
{
vis[tx][ty] = 1;
lis[tail].x = tx;
lis[tail].y = ty;
pre[tail] = head;
tail++;
}
}
head++;
}
return;
}
int main()
{
memset(vis,0,sizeof(0));
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
scanf("%d",&a[i][j]);
bfs();
return 0;
}