POJ 3984 迷宫问题 (BFS)
来源:互联网 发布:六小龄童知乎扒皮 编辑:程序博客网 时间:2024/05/16 08:58
题意:给一个5*5的迷宫,问从左上角走到右下角的最短路径,并输出该路径。
解析:言归正传,这道水题中的水题,只需要简单的BFS,再记录一下路径即可。关于记录路径,今天刚学的,就是开一个pre数组,记录前一个状态,需要输出时,利用回溯即可全部输出路径。
AC代码:
#include<iostream>#include<cstdio>using namespace std;const int INF = 100000000;const int maxn = 10;typedef struct{ int x,y,pre;}point;point q[maxn];int front=0,rear=1,sx,sy,ex,ey;int arr[maxn][maxn];int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};int N,M;void output(int i){ if(q[i].pre != -1) { output(q[i].pre); printf("(%d, %d)\n",q[i].x,q[i].y); }}void bfs(int sx,int sy){ q[front].x = sx; q[front].y = sy; q[front].pre = -1; arr[sx][sy] = 1; while(front < rear) { for(int i=0;i<4;i++) { int nx = q[front].x + dx[i]; int ny = q[front].y + dy[i]; if(nx<0 || nx>=5 || ny<0 || ny>=5 || arr[nx][ny]) continue; else { arr[nx][ny] = 1; q[rear].x = nx; q[rear].y = ny; q[rear++].pre = front; } if(nx == 4 && ny == 4) output(front); } front++; }}int main(){ for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&arr[i][j]); printf("(0, 0)\n"); bfs(0,0); printf("(4, 4)\n"); return 0;}
更新:
上面是手动模拟的队列实现的BFS,下面用STL中的队列实现了一次,但是打印路径就显得没这么方便了。开一个pair到par的映射,因为pair可以直接判相等,开结构体会报错。。。
#include <cstdio>#include <queue>#include <cstring>#include <map>#include <utility>using namespace std;int m[6][6];int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};int sx, sy, ex, ey;bool vis[6][6];typedef pair<int, int> PP;map<PP, PP> p;void print_pre(PP x){ if(x == PP(-1, -1)) return ; print_pre(p[x]); printf("(%d, %d)\n", x.first, x.second);}void bfs(){ queue<PP> q; q.push(PP(sx, sy)); p[PP(sx, sy)] = PP(-1, -1); p[PP(ex, ey)] = PP(-1, -1); vis[sx][sy] = true; while(!q.empty()){ PP now = q.front(); q.pop(); for(int i=0; i<4; i++){ int x = now.first + dir[i][0]; int y = now.second + dir[i][1]; if(x < 0 || x >= 5 || y < 0 || y >= 5) continue; if(m[x][y] == 1) continue; if(vis[x][y]) continue; vis[x][y] = true; q.push(PP(x, y)); p[PP(x, y)] = now; if(x == ex && y == ey){ print_pre(now); printf("(4, 4)\n"); return ; } } }}int main(){ #ifdef sxk freopen("in.txt", "r", stdin); #endif //sxk for(int i=0; i<5; i++) for(int j=0; j<5; j++) scanf("%d", &m[i][j]); sx = sy = 0; ex = ey = 4; memset(vis, false, sizeof(vis)); bfs(); return 0;}
0 0
- POJ 3984 迷宫问题 (BFS,水题)
- poj 3984 -- 迷宫问题 (bfs)
- POJ 3984 迷宫问题 (BFS)
- poj 3984 迷宫问题 (bfs入门)
- poj 3984 迷宫问题(bfs)
- POJ 3984 - 迷宫问题(BFS)
- POJ 题目3984 迷宫问题(BFS)
- Poj 3984 迷宫问题(BFS)
- POJ 3984 迷宫问题(BFS)
- POJ 3984 迷宫问题 (bfs 水)
- POJ 3984 迷宫问题(bfs)
- poj 3984 迷宫问题 (BFS+递归)
- poj 3984 迷宫问题(BFS+回溯)
- POJ 3984 迷宫问题(BFS)
- POJ 3984 迷宫问题 (DFS+BFS)
- POJ 3984 迷宫问题(bfs)
- POJ 3984 迷宫问题(BFS)
- POJ 3984 迷宫问题 (BFS)
- 关于构造方法
- poj3468(线段树成段更新模板题)
- putty 提示:network error:connect refused
- Windows64和32位系统 下注册自己的DLL
- HBase 系统架构
- POJ 3984 迷宫问题 (BFS)
- 数据库操作(存着用来复制省的每次写)
- PHP编写的小应用——计算器
- Mysql 安装完毕运行时没有 mysql 和 performance_schema 数据库
- 构造函数 init
- linux 下apache+tomcat集群总结
- java中对象的引用与赋值
- BUPT暑假排位第四场
- 2014年最新前端开发面试题(题目列表+答案 完整版)