POJ 3984 BFS 打印路径
2015-07-17 15:09
288 查看
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
Sample Output
[code]
定义一个二维数组:
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打印路径就是记录父亲结点,然后从后往前找出路径。再反过来输出一遍。
[code]
#include <iostream> #include <algorithm> #include <string.h> #include <queue> #include <map> #define ll long long #include<cstdio> using namespace std; int m[9][9]; int ans[30]; int dis [4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; int fa[9][9]; struct node { int x,y; }; queue<node> q; int flag=0; int bfs( node start ) { fa[0][0] = 0; q.push(start); while(!q.empty()) { node tmp = q.front(); q.pop(); for(int i = 0;i < 4;i ++) { int xx = tmp.x + dis[i][0]; int yy = tmp.y + dis[i][1]; if(xx>=0&&xx<5&&yy>=0&&yy<5&&!m[xx][yy]) { m[xx][yy] = 1; node next; next.x = xx; next.y = yy; fa[xx][yy] = tmp.x * 10 + tmp.y; q.push(next); } if(xx==4&&yy==4) { flag=1; fa[xx][yy] = tmp.x * 10 + tmp.y; break; } } if(flag) break; } return 0; } int main() { for(int i=0;i<5;i++) { for(int j=0;j<5;j++) cin>>m[i][j]; } node ddd; ddd.x = 0 , ddd.y = 0 ; bfs(ddd); int cnt = 0; int ans[111]; int dx = 4, dy = 4; int ddx,ddy; while(dx!=0||dy!=0) { ans[cnt++] = dx*10 + dy; ddx = fa[dx][dy]/10; //这个地方注意不要改变dx的值,否则fa[dx][dy]的值会变 ddy = fa[dx][dy]%10; dx=ddx,dy=ddy; } printf("(%d, %d)\n",0,0); for(int i=cnt - 1;i>=0;i--) { printf("(%d, %d)\n",ans[i]/10,ans[i]%10); } return 0; }
相关文章推荐
- codeforce 551C GukiZ hates Boxes
- hdu 1513 Palindrome(LCS)
- 基于C/C++的读取文件夹下所有文件(图片、文档等)的代码
- [delphi技术]Delphi常见图象格式转换技术
- 弟弟的作业
- IOS中的模糊效果
- C#异步执行任务的方法
- snmpd占用CPU过高
- ChildActionOnly和ActionName的用法
- dd大牛的背包九讲
- Cisco Packet Tracer6.0安装及汉化
- 本人为巨杉数据库(开源NoSQL)写的C#驱动,支持Linq,全部开源,已提交github
- C# 百度语音合成
- jQuery EasyUI实现全部关闭tabs
- Suppress user properties/ custom fields when print in Outlook
- 自己写的类似UITextView的类,实现UIKeyInput协议
- ios 程序后台运行
- java 利用系统WinRAR解压缩(zip/rar压缩文件)
- 改进Spring中的分页技术
- 南邮的面积