您的位置:首页 > 其它

poj_3984_迷宫问题(搜索)

2013-05-28 13:10 441 查看
分类:搜索
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)

分析:

用BFS进行搜索,再递归输出路线即可。

总结:

BFS还是不熟练,仍需继续巩固。

代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int map[10][10];
int vis[100];
int pre[100];
int dirs[4][2]={{1,0},{0,1},{-1,0},{0,-1}};//四个方向

bool isfun(int r,int c){//判断是否能走
if(r<0||r>4||c<0||c>4){
return false;
}
if(map[r][c]==1){
return false;
}
return true;
}

void bfs(){
queue<int> q;
memset(vis,0,sizeof(vis));
pre[0]=-1;
vis[0]=true;
q.push(0);//从左上角开始
int now,next;
int r,c,rr,cc;
while(!q.empty()){
now=q.front();
q.pop();
r=now/5;
c=now%5;
for(int i=0;i<4;i++){
rr=r+dirs[i][0];
cc=c+dirs[i][1];
next=5*rr+cc;//因为是一位数组,所以将next设置成这样
if(isfun(rr,cc)&&!vis[next]){
pre[next]=now;
if(next==24) return;//结束
vis[next]=true;
q.push(next);//放入队中,发散节点
}
}
}
}

void print(int n){
if(pre
!=-1)
print(pre
);//递归
printf("(%d, %d)\n",n/5,n%5);
}

int main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
scanf("%d",&map[i][j]);
}
}
bfs();
print(24);
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: