hdoj 1242 Rescue
2012-08-24 16:13
232 查看
题目大意:一个迷宫,多个朋友去解救一个人,#表示障碍,不能走,r表示朋友,x表示守卫,走到这位置得消耗2个单元,其他只消耗一个单元,a表示要解决的人。求多个朋友解救到这个人的最短时间
解题思路:因为有多个起点,我们可以反过来以a为起点,求到达任意一个r的最短时间。
用宽度优先遍历。。。。但是有x节点,消耗2个时间单元,所以保存每次走过的格子状态,即每个格子当前能到达的最短时间。
宽度优先遍历时,若这个格子节点的值比当前走到的时间长,则更新这个格子,然后扩展这个节点。
解题思路:因为有多个起点,我们可以反过来以a为起点,求到达任意一个r的最短时间。
用宽度优先遍历。。。。但是有x节点,消耗2个时间单元,所以保存每次走过的格子状态,即每个格子当前能到达的最短时间。
宽度优先遍历时,若这个格子节点的值比当前走到的时间长,则更新这个格子,然后扩展这个节点。
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; struct node { int x, y, step; }; const int maxn = 210; int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int n, m, num, sx, sy, minv; char prison[maxn][maxn]; int val[maxn][maxn]; bool bfs(); int main() { while(scanf("%d %d", &n, &m) != EOF) { num = 0; memset(val, 0, sizeof(val)); for(int i = 0; i < n; i++) { scanf("%s", prison[i]); for(int j = 0; j < m; j++) { if(prison[i][j] == 'a') { sx = i; sy = j; } val[i][j] = 0x7fffffff; } } val[sx][sy] = 0; if(bfs()) printf("%d\n", minv); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; } bool bfs() { queue<node> que; node s, next; s.x = sx; s.y = sy; s.step = 0; que.push(s); minv = 0x7fffffff; while(!que.empty()) { node tmp = que.front(); que.pop(); if(prison[tmp.x][tmp.y] == 'r') minv = min(minv, tmp.step); for(int i = 0; i < 4; i++) { next.x = tmp.x + dir[i][0]; next.y = tmp.y + dir[i][1]; next.step = tmp.step + 1; if(next.x >= 0 && next.x < n && next.y >=0 && next.y < m && prison[next.x][next.y] != '#') { if(prison[next.x][next.y] == 'x') next.step++; if(val[next.x][next.y] > next.step) { val[next.x][next.y] = next.step; que.push(next); } } } } if(minv != 0x7fffffff) return true; return false; }
相关文章推荐
- hdoj 1242 Rescue
- HDU/HDOJ 1242 Rescue 典型的迷宫广度优先搜索题
- HDOJ-1242 Rescue
- HDOJ 1242 Rescue 优先队列+bfs
- hdoj-1242-Rescue(DFS)
- HDOJ 题目1242 Rescue(BFS)
- hdoj 1242 Rescue
- Hdoj 1242 Rescue
- hdoj1242-【Rescue】
- HDOJ-1242(Rescue)(bfs+优先队列)
- HDOJ-1242 Rescue -------BFS
- hdoj 1242 Rescue [BFS]
- HDOJ 1242 Rescue
- HDOJ-1242 Rescue(广搜,剪枝)
- HDOJ 1242 Rescue(BFS+优先对列)
- HDOJ 1242 Rescue
- hdoj1242 Rescue
- 【记忆化DFS】HDOJ1242 Rescue
- HDOJ/HDU 1242 Rescue(经典BFS深搜-优先队列)
- HDOJ1242Rescue(BFS+优先队列)