迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5387 | Accepted: 3066 |
Description
定义一个二维数组:
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)
记录前驱,最后从(5,5)返回值(1,1)输出.
#include<iostream>
#include <cstring>
#include <queue>
#include <cstdio>
using namespace std;
const int MAXN = 10;
int maps[MAXN][MAXN];
int visited[MAXN][MAXN];
int moves[4][2] = {-1,0,1,0,0,-1,0,1};
int ans;
struct Point{
int x;
int y;
int step;
};
queue<Point>Q;
Point pre[MAXN][MAXN],path[30];
void BFS()
{
while(!Q.empty())
Q.pop();
Point a,b;
a.x = 0;
a.y = 0;
a.step = 0;
visited[0][0] = 1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x==4&&a.y==4)
{
break;
}
for(int i=0;i<4;i++)
{
b.x = a.x + moves[i][0];
b.y = a.y + moves[i][1];
if(b.x>=0&&b.y<5&&a.x>=0&&a.y<5&&!visited[b.x][b.y]&&!maps[b.x][b.y])
{
pre[b.x][b.y] = a;
visited[b.x][b.y] = 1;
b.step = a.step + 1;
Q.push(b);
}
}
}
ans = a.step;
for(int i=ans;i>=0;i--)
{
path[i] = a;
a = pre[a.x][a.y];
}
for(int i=0;i<=ans;i++)
{
printf("(%d, %d)\n",path[i].x,path[i].y);
}
}
int main()
{
freopen("in.txt","r",stdin);
int i,j;
memset(pre,0,sizeof(pre));
memset(maps,0,sizeof(maps));
memset(visited,0,sizeof(visited));
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
cin>>maps[i][j];
}
}
BFS();
//cout<<ans<<endl;
}