迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10318 | Accepted: 6124 |
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)
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
struct N{
int x,y,t;
}List[100][100];
bool ans[100][100];
int maze[100][100];
int go[][2]={-1,0,1,0,0,1,0,-1};
queue<N> Q;
int n,m;
int BFS(int n,int m){
while(Q.empty()==false){
N now =Q.front();
Q.pop();
for(int i=0;i<4;i++){
int a=now.x+go[i][0];
int b=now.y+go[i][1];
if(a<0||a>=n||b<0||b>=m) continue;
if(ans[a][b]==true) continue;
if(maze[a][b]==1)continue;
N tmp;
tmp.x=a;
tmp.y=b;
tmp.t=now.t+1;
Q.push(tmp);
List[a][b].x=now.x;
List[a][b].y=now.y;
ans[a][b]=true;
if(a==n-1&&b==m-1)
return tmp.t;
}
}
return -1;
}
void print(int sx,int sy)
{
if(sx==0&&sy==0){
printf("(%d,%d)",sx,sy);
return;
}
print(List[sx][sy].x,List[sx][sy].y);
printf("(%d,%d)\n",sx,sy);
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
scanf("%d",&maze[i][j]);
ans[i][j]=false;
}
while(Q.empty()==false) Q.pop();
N tmp;
tmp.x=tmp.y=tmp.t=0;
ans[0][0]=true;
Q.push(tmp);
printf("%d\n",BFS(n,m));
print(4,4);
}
system("pause");
return 0;
}