迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 33042 | Accepted: 18849 |
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<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int m=0,n=1;
int num[5][5],cnt[5][5];
int f[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
struct point{
int x,y,pre;
}p[100];
void prt(int r){
if(p[r].pre!=-1){
prt(p[r].pre);
printf("(%d, %d)\n",p[r].x,p[r].y);
}
}
void bfs(int a,int b){
cnt[a][b]=1;
p[m].x=a;
p[m].y=b;
p[m].pre=-1;
while(m<n){
for(int i=0;i<4;i++){
int t=p[m].x+f[i][0];
int q=p[m].y+f[i][1];
if((t>=0&&t<5)&&(q>=0&&q<5)&&(cnt[t][q]==0)&&(num[t][q]==0)){
cnt[t][q]=1;
p[n].x=t;
p[n].y=q;
p[n].pre=m;
if(t==4&&q==4){
prt(n);
break;
}
n++;
}
}
m++;
}
}
int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%d",&num[i][j]);
}
}
memset(cnt,0,sizeof(cnt));
printf("(0, 0)\n");
bfs(0,0);
return 0;
}
扫描二维码关注公众号,回复:
2826092 查看本文章