poj_3984_迷宫问题(搜索)
2013-05-28 13:10
441 查看
分类:搜索
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
Sample Output
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; }
相关文章推荐
- [搜索] POJ 3984 迷宫问题
- poj 3984 迷宫问题 宽度搜索 一个终点
- [kuangbin带你飞]专题1 简单搜索 K - 迷宫问题 POJ - 3984
- 搜索练习3 /poj.org/problem 3984 迷宫问题/bfs 回溯找路经
- POJ 3984 迷宫问题 搜索题解
- poj 3984 迷宫问题 BFS 图的广度优先搜索
- [kuangbin带你飞]专题一 简单搜索K - 迷宫问题(POJ 3984)
- K - 迷宫问题 POJ - 3984(广度搜索)
- POJ 3984 迷宫问题(记录路径的搜索)
- POJ 3984 迷宫问题(广度搜索)
- POJ 3984 迷宫问题(kuangbin带你飞 专题一:简单搜索)
- [kuangbin]专题一 简单搜索 K - 迷宫问题 POJ - 3984
- 搜索最短路径:迷宫问题 POJ - 3984
- [kuangbin带你飞]专题一 简单搜索 K - 迷宫问题 POJ 3984
- POJ - 3984 迷宫问题 [kuangbin带你飞]专题一 简单搜索
- poj 3984 迷宫问题 —— 典型搜索--DFS递归
- poj 3984 迷宫问题 —— 典型搜索--DFS递归
- poj3984——迷宫问题(BFS)
- POJ 3984 迷宫问题<记忆BFS>
- POJ - 3984----迷宫问题