poj3984-bfs模板详解
来源:互联网 发布:飞客数据恢复怎么样 编辑:程序博客网 时间:2024/06/05 08:05
题目:一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
要求打印最短路线坐标,可以套用bfs模板做的简单题,很适合用来学习bfs,可以自己手动debug一下来体会bfs。
其中比较难理解的就是pre[]数组了,可以看做是一个数组模拟的树状结构,用来记录bfs过程中每一次中,上一步和下一步的联系。
以这个为例
上一行是最短路线坐标,下一行是pre数组中存的数,0->(1,0),1->(2,0)依次类推,理论上3->(3,0)但我们不需要那条路。
打印的时候用了一个递归,像栈一样,从里往外打印。
因为head此时等于17
pre[17]=14 ->pre[14]=11->pre[11]=8………
一直推到pre[1]=0为止。
#include <iostream>#include <cstdio>#include <cstring>using namespace std;int a[5][5],vis[5][5],pre[30];//分别代表迷宫,是否走过,走的路线int p[] = {0,1,0,-1},q[] = {1,0,-1,0}; struct cam{ int x; int y;} lis[30]; //记录走过的坐标void print(int x){ int t; t=pre[x]; if(t==0) { printf("(0, 0)\n"); printf("(%d, %d)\n",lis[x].x,lis[x].y); return; } else print(t); printf("(%d, %d)\n",lis[x].x,lis[x].y); return;}void bfs(){ int head,tail; int x,y,tx,ty; head = 0; tail = 1; lis[0].x = 0; lis[0].y = 0; pre[0] = -1; while(head < tail) { x = lis[head].x; y = lis[head].y; if(x==4 && y==4) { print(head); return; } for(int i=0; i<4; i++) { tx = x+p[i]; ty = y+q[i]; if(tx<0 || tx>4 || ty<0 || ty>4 || a[tx][ty]==1) continue; if(!vis[tx][ty]) { vis[tx][ty] = 1; lis[tail].x = tx; lis[tail].y = ty; pre[tail] = head; tail++; } } head++; } return;}int main(){ memset(vis,0,sizeof(0)); for(int i=0; i<5; i++) for(int j=0; j<5; j++) scanf("%d",&a[i][j]); bfs(); return 0;}
0 0
- poj3984-bfs模板详解
- poj3984--BFS
- bfs poj3984
- POJ3984 迷宫问题 BFS
- bfs 管窥 poj3984
- POJ3984 迷宫问题 BFS
- poj3984 迷宫问题(BFS)
- POJ3984 迷宫问题【BFS】
- poj3984迷宫问题(bfs)
- POJ3984 迷宫问题【BFS】
- POJ3984 BFS 输出路径
- poj3984 迷宫问题 bfs
- POJ3984 迷宫问题【BFS】
- POJ3984 迷宫问题(BFS)
- poj3984迷宫问题 bfs
- poj3984(BFS)迷宫路径
- poj3984 迷宫问题(BFS)
- POJ3984 迷宫问题【水BFS】
- AutoCAD.NET API 最新教程下载及在线视频教程DevTV 第2讲 用户交互
- Log4j配置
- mysql server has gone away发生的原因以及解决方案
- jquery控制图片由中心点缓慢变大效果
- 问题 F: 小明与隔壁老王之间不得不说的故事
- poj3984-bfs模板详解
- DOM操作要点
- 深度学习教程:从感知器到深层网络
- 写给自己
- AutoCAD.NET API 最新教程下载及在线视频教程DevTV 中文版第1讲 入门
- 微服务部署集群整套方案
- 递归算法之汉诺塔问题
- border-radius的趣味妙谈
- lucene教程--全文检索技术详解