uva 11624 Fire!(多源BFS)
2015-08-07 20:49
543 查看
uva 11624 Fire!
题目大意:J在迷宫里工作,有一天迷宫起火了,火源有多处。每过一秒,火源都会向四个方向蔓延,J也会向四个方向移动,问J能不能跑出去,能的话输出他跑出去的最短时间,否则输出“IMPOSSIBLE”
解题思路:先进行一次BFS,找出每一点火焰蔓延到该处的最短时间。然后根据这张“火势图”,对J的行进路线进行BFS。注意J在边缘的时候,以及没有火源的时候。
[code]#include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <cstdlib> #include <queue> using namespace std; const int N = 1005; typedef long long ll; int n, m; int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; struct Node{ int x, y, d; bool operator < (const Node& x) const { return d > x.d; } }; Node s; int cnt; int fire ; queue<Node> Q; priority_queue<Node> Q2; char map ; int BFS_F() { while (!Q.empty()) { Node p = Q.front(); Q.pop(); int px, py; for (int i = 0; i < 4; i++) { px = p.x + dir[i][0], py = p.y + dir[i][1]; if (px < 0 || py < 0 || px >= n || py >= m) continue; if (map[px][py] == '#') continue; map[px][py] = 'F'; if (fire[px][py] > p.d + 1 || fire[px][py] == -1) { fire[px][py] = p.d + 1; Q.push((Node){px, py, p.d + 1}); } } } } int BFS() { while (!Q2.empty()) { Node p = Q2.top(); Q2.pop(); for (int i = 0; i < 4; i++) { int px = p.x + dir[i][0], py = p.y + dir[i][1]; if (px < 0 || py < 0 || px >= n || py >= m) continue; if (map[px][py] == '#' || map[px][py] == 'J') continue; if (fire[px][py] >= p.d + 2) { if (px == 0 || py == 0 || px == n - 1 || py == m - 1) { return p.d + 1; } map[px][py] = 'J'; Q2.push((Node){px, py, p.d + 1}); } } } return 0; } int main() { int T; scanf("%d", &T); while (T--) { cnt = 0; memset(fire, -1, sizeof(fire)); while (!Q.empty()) Q.pop(); while (!Q2.empty()) Q2.pop(); scanf("%d %d\n", &n, &m); int flag = 0, flag2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%c", &map[i][j]); if (map[i][j] == 'J') { if (i == 0 || j == 0 || i == n - 1 || j == m - 1) { flag = 1; } Q2.push((Node){i, j, 0}); } else if (map[i][j] == 'F') { flag2 = 1; fire[i][j] = 0; Q.push((Node){i, j, 0}); } } getchar(); } if (!flag2) memset(fire, 0x3f, sizeof(fire)); if (flag) { printf("1\n"); continue; } BFS_F(); int B = BFS(); if (!B) { printf("IMPOSSIBLE\n"); } else printf("%d\n", B + 1); } return 0; }
相关文章推荐
- hdu 2203 亲和串
- Can not find the tag library descriptor for "/struts-tags"
- C/C++,Windows/MFC, char, wchar_t, TCHAR 字符全总结 & c++字符串操作经验集
- 杭电 2549 壮志难酬 水题
- virtools贴吧
- [笔记]binaryheap
- Java线程:线程的同步与锁
- HDOJ 1253 胜利大逃亡 (三维BFS+技巧)
- 蓝牙技术转载源码
- pat 1085. Perfect Sequence (25)
- virtools3.0-3.5 下载地址
- (转)Java线程:线程的同步与锁
- uva 11040 - Add bricks in the wall
- 线程栈模型与线程的变量、线程状态转换
- java Socket多线程聊天程序(适合初学者)
- (转)线程栈模型与线程的变量、线程状态转换
- 如何删除 CentOS 6 更新后产生的多余的内核?
- 扒照片
- struts基本开发流程
- poj 2406 Power Strings (kmp)