K - 迷宫问题 POJ - 3984
定义一个二维数组:
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)
思路: 重点是存一下每个点的上一个点 ,这样就能得到路径了,具体看代码。
注:其中用到了我很喜欢的一个回溯方法,那个ty pre[]
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef struct node {
int x,y;
} ty;
int a[6][6];
ty pre[6][6]; // 用来存某个点的上一个点的位置
int via[6][6];
ty t,d;
void pri(int a, int b) // 用递归来倒叙输出答案
{
if ( a==0 && b==0 ) {
return ;
}
pri(pre[a][b].x,pre[a][b].y);
cout << "(" << a << ", " << b << ")" << endl;
}
void bfs()
{
int next[4][2] = {
{0,1},{0,-1},{1,0},{-1,0}
};
queue <ty> Q;
t.x = 0;
t.y = 0;
Q.push(t);
via[0][0] = 1;
while ( !Q.empty() ) {
t = Q.front();
Q.pop();
if ( t.x==4 && t.y==4 ) {
return ;
}
for ( int i=0; i<4; i++ ) {
d.x = t.x + next[i][0];
d.y = t.y + next[i][1];
if ( d.x<0 || d.y<0 || d.x>4 || d.y>4 ) {
continue ;
}
if ( a[d.x][d.y]==0 && via[d.x][d.y]==0 ) {
via[d.x][d.y] = 1;
Q.push(d);
pre[d.x][d.y].x = t.x;
pre[d.x][d.y].y = t.y;
}
}
}
}
int main()
{
int n = 5;
int i,j;
for ( i=0; i<n; i++ ) {
for ( j=0; j<n; j++ ) {
cin >> a[i][j];
}
}
memset(via,0,sizeof(via));
bfs();
cout << "(0, 0)" << endl;
pri(4,4);
return 0;
}