UVA 11624 Fire!(BFS)
2016-08-11 23:44
363 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671
题意:J需要逃出矩阵,只有走到矩阵边即算成功。但是矩阵中存在几个F代表火,火每一秒向四周扩散,问J能否逃出?求最短路径。
思路一:先对火进行搜索,记录火到每个点的最短时间。然后对J进行搜索,J每次到一个点,判断J到这个点的时间是否早于火到达的时间。若早即可走。
思路二:对人和火进行同时搜索,每次搜索先处理火的,再处理人的。判断同思路一。
代码:
题意:J需要逃出矩阵,只有走到矩阵边即算成功。但是矩阵中存在几个F代表火,火每一秒向四周扩散,问J能否逃出?求最短路径。
思路一:先对火进行搜索,记录火到每个点的最短时间。然后对J进行搜索,J每次到一个点,判断J到这个点的时间是否早于火到达的时间。若早即可走。
思路二:对人和火进行同时搜索,每次搜索先处理火的,再处理人的。判断同思路一。
代码:
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <math.h> #include <queue> using namespace std; const int INF = 0x3f3f3f3f; const int N = 1e3 + 10; struct Node { int x, y; int step; }; int r, c; vector<Node> f; int fire ; int dis ; char _map ; int x[4] = {0, 1, 0, -1}; int y[4] = {1, 0, -1, 0}; bool safe(Node now) { if (now.x == 0 || now.x == r - 1 || now.y == 0 || now.y == c - 1) return true; return false; } int bfs(Node s) { queue<Node> q, p; for (int i = 0; i < f.size(); i++) { p.push(f[i]); fire[f[i].x][f[i].y] = 0; } q.push(s); dis[s.x][s.y] = 0; while (!q.empty()) { int nt = q.front().step; // 记录当前搜索的时间 while (!p.empty() && p.front().step <= nt) { // 处理当前时间的火 Node nf = p.front(); p.pop(); for (int i = 0; i < 4; i++) { Node tf; tf.x = nf.x + x[i]; tf.y = nf.y + y[i]; tf.step = nf.step + 1; if (tf.x >= 0 && tf.x < r && tf.y >= 0 && tf.y < c && _map[tf.x][tf.y] != '#' && fire[tf.x][tf.y] > tf.step) { fire[tf.x][tf.y] = tf.step; p.push(tf); } } } while (!q.empty() && q.front().step <= nt) { // 处理当前时间的人 Node nj = q.front(); q.pop(); if (safe(nj)) return nj.step; for (int i = 0; i < 4; i++) { Node tj; tj.x = nj.x + x[i]; tj.y = nj.y + y[i]; tj.step = nj.step + 1; if (tj.x >= 0 && tj.x < r && tj.y >= 0 && tj.y < c && _map[tj.x][tj.y] != '#' && dis[tj.x][tj.y] > tj.step && fire[tj.x][tj.y] > tj.step) { dis[tj.x][tj.y] = tj.step; q.push(tj); } } } } return -1; } int main() { int t_case; scanf("%d", &t_case); for (int i_c = 0; i_c < t_case; i_c++) { scanf("%d%d", &r, &c); for (int i = 0; i < r; i++) scanf("%s", _map[i]); Node st; f.clear(); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (_map[i][j] == 'J') { st.x = i, st.y = j, st.step = 0; } else if (_map[i][j] == 'F') { Node t; t.x = i, t.y = j, t.step = 0; f.push_back(t); } } } memset(dis, INF, sizeof(dis)); memset(fire, INF, sizeof(fire)); int res = bfs(st); if (res == -1) printf("IMPOSSIBLE\n"); else printf("%d\n", res + 1); } return 0; }
相关文章推荐
- uva 11624 - Fire!(BFS)
- UVA-11624 Fire!(两次BFS)
- UVa 11624 Fire! ( BFS )
- UVA 11624 Fire bfs水题
- UVA 11624 Fire!(双点bfs)
- UVA - 11624 Fire!两个bfs
- 【UVA】 11624 Fire!【BFS】
- uva 11624 Fire!(bfs预处理)
- UVA - 11624 Fire!两个bfs
- UVA 11624 fire! (bfs)
- UVA 11624 Fire!(bfs)
- Uva11624 Fire(bfs 搜索)
- UVA 11624-Fire!-BFS-
- UVA-11624-Fire!(多点BFS)
- uva 11624 Fire!(多源BFS)
- UVA - 11624 Fire!两个bfs
- UVA11624 Fire BFS
- UVA - 11624 Fire! BFS
- uva11624 Fire! (双bfs)
- UVA 11624 Fire!(两次BFS、超级源)