POJ 3984 迷宫问题【迷宫最短路径 bfs】
2015-08-02 15:28
429 查看
POJ 3984 迷宫问题【迷宫最短路径 bfs】
题目链接 http://poj.org/problem?id=3984#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int MAXL = 10; // 矩阵最大宽度 char maze[MAXL][MAXL]; // 迷宫 bool vis[MAXL][MAXL]; // 访问标记 int n, m; // 迷宫的长和宽 int dirx[4] = {0, 1, 0, -1}; int diry[4] = {1, 0, -1, 0}; // 移动方向 typedef struct point{ int x, y; }P; // 坐标 P path[MAXL*MAXL]; // 路径队列 int pre[MAXL*MAXL]; // 记录父结点 P start, goal; // 起点 终点 P current, next; // 当前坐标 下一步的坐标 void Output(){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ printf("%d\t", maze[i][j]); } printf("\n"); } } void Input(){ memset(maze, 0, sizeof(maze)); memset(vis, 0, sizeof(vis)); n = 5; m = 5; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ scanf("%c", &maze[i][j]); maze[i][j] -= '0'; if(j != n-1) getchar(); // 输入空格 } getchar(); // 输入回车 } //Output(); } void Print(int pos){ if(pos == 0){ // 输出起点 printf("(%d, %d)\n", path[pos].x, path[pos].y); } else{ int pointer; pointer = pre[pos]; // 父结点在路径中的位置 Print(pointer); printf("(%d, %d)\n", path[pos].x, path[pos].y); } } void bfs(){ start.x = 0; start.y = 0; goal.x = n-1; goal.y = m-1; int head, tail; // 队头 队尾 int x, y, xx, yy; // x,y是当前坐标 xx,yy是下一步的坐标 head = 0; path[0].x = start.x; path[0].y = start.y; pre[0] = -1; vis[start.x][start.y] = true; tail = 1; // 起点入队 while(head < tail){ // 如果队列不为空 x = path[head].x; y = path[head].y; if(x == goal.x && y == goal.y){ Print(head); // 走到终点 打印最短路径 return; } for(int i = 0; i < 4; i++){ xx = x + dirx[i]; yy = y + diry[i]; if(xx >= 0 && xx < n && yy >= 0 && yy < m && maze[xx][yy] == 0 && !vis[xx][yy]){ vis[xx][yy] = true; path[tail].x = xx; path[tail].y = yy; pre[tail] = head; tail++; // 当前坐标入队 } } head++; // 四个方向都走过后元素出队 } } int main(){ Input(); bfs(); return 0; }
还有一个使用queue的版本,来自网络:
http://m.blog.csdn.net/blog/yzj577/37997073
相关文章推荐
- Surrounded Regions
- Word Ladder, Gray Code
- Hdu2444二分图
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记
- [LeetCode] Binary Tree Level Order Traversal
- [LeetCode] Binary Tree Level Order Traversal II
- 关于BFS搜索的思想, 最简单的水题,不过深有体会啊。
- Word Ladder II
- Surrounded Regions
- vijosP1016北京2008的挂钟 BFS + 优先队列
- FZU 2169 shadow
- 1215迷宫问题(wikioi)突破过程
- Catch That Cow