K - 迷宫问题
POJ - 3984Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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在结构体里多放一个保存节点父亲的变量就好了。
ACcode:
#include <cstdio>
int map[5][5];
int book[5][5];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
int head=0,tail=0;
struct __node{
int x;
int y;
int s;
int f;//找父亲
}node[30];
int bfs()
{
node[0].x=0;
node[0].y=0;
node[0].s=0;
node[0].f=-1;
tail++;
book[0][0]=1;
while(head<tail)
{
for(int i=0;i<4;i++)
{
int tx=node[head].x+dx[i];
int ty=node[head].y+dy[i];
if(tx<0 || tx>=5 || ty <0 || ty >=5 )continue;
if(map[tx][ty]==1 || book[tx][ty]==1)continue;
book[tx][ty]=1;
node[tail].x=tx;
node[tail].y=ty;
node[tail].s=node[head].s+1;
node[tail].f=head;
tail++;
if(tx==4 && ty==4) return node[tail-1].f;
}
head++;
}
return 0;
}
int main()
{
int path[25];
int k=0;
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&map[i][j]);
int ans=bfs();
while(ans!=0) //往上找父亲 并保存.
{
path[k++]=ans;
ans=node[ans].f;
}
printf("(0, 0)\n");
for(int i=k-1;i>=0;i--)
{
printf("(%d, %d)\n",node[path[i]].x,node[path[i]].y);
}
printf("(4, 4)\n");
}