POJ 3984 迷宫问题
2016-04-02 09:30
288 查看
迷宫问题
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
Sample Output
用BFS求最短路径,记录每一个状态之前的状态,输出路径即可
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 13710 | Accepted: 8192 |
定义一个二维数组:
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求最短路径,记录每一个状态之前的状态,输出路径即可
#include <cstdio> #include <cstring> using namespace std; struct cam { int x; int y; }list[100]; int map[5][5]; int vis[5][5]; int pre[100]; //记录每一个状态的前一个状态 int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; int go(int x, int y) { if (x >= 0 && x < 5 && y >= 0 && y < 5 && map[x][y] == 0) return 1; return 0; } void print(int x) { int t; t = pre[x]; if (t == 0){ printf("(0, 0)\n"); printf("(%d, %d)\n", list[x].x, list[x].y); return; } else print(t); printf("(%d, %d)\n", list[x].x, list[x].y); } void bfs() { int x, y, xx, yy; int head = 0, tail = 1; memset(vis, 0, sizeof(vis)); list[0].x = 0; list[0].y = 0; pre[0] = -1; while (head < tail){ x = list[head].x; y = list[head].y; if (x == 4 && y == 4){ print(head); return; } for (int i = 0; i < 4; i++){ xx = x + dir[i][0]; yy = y + dir[i][1]; if (!vis[xx][yy] && go(xx, yy)){ vis[xx][yy] = 1; list[tail].x = xx; list[tail].y = yy; pre[tail] = head; tail++; } } head++; } return; } int main() { for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++){ scanf("%d", &map[i][j]); } } bfs(); return 0; }
相关文章推荐
- 算法训练 进制转换
- eclipse如何修改dynamic web module version
- 三言两语说shader(四)渲染流水线及相关
- Python如何模拟发送form-data请求
- 神庙逃亡
- 算法训练 字串统计
- 算法训练 字符删除
- c++面试题
- 随谈 error:unknown filesystem grub rescue解决办法
- [从头学数学] 第157节 概率初步 小结与复习题
- springMVC整合xStream
- 算法训练 反置数
- Android相对布局属性全解
- Linux内核分析之六——进程的描述与进程的创建
- ZOJ 1151 Word Reversal
- 算法训练 数位分离
- C++智能指针与返回局部指针测试
- 算法训练 薪水计算
- 超简单小算法求圆面积(测多组数据及小用一下正则表达式)(入门)
- 算法训练 整除问题