https://vjudge.net/problem/UVA-11624
题意:
有一个大火蔓延的迷宫,迷宫中有障碍格,而所有着火的格子都会往四周蔓延。求出到达边界格子时的最短时间。
思路:
复杂了一点的迷宫。
在bfs之前,我们首先需要计算出火势蔓延的情况,火势每次向四周蔓延一个格子,所以这也是一个最短路问题,也用一次bfs,计算出每个空白格子着火时的时间。这样,当我们第二次bfs去计算走出迷宫的时间时,对于每一个可走的格子,我们只需要判断在此时该格子是否着火,如果还未着火,则该格子是可以走的。
1 #include<iostream> 2 #include<algorithm> 3 #include<queue> 4 #include<cstring> 5 using namespace std; 6 7 const int maxn = 1000 + 5; 8 9 int map[maxn][maxn]; 10 int fire[maxn][maxn]; 11 int vis[maxn][maxn]; 12 13 int dx, dy; 14 int n, m; 15 16 int sx[] = { 0, 0, 1, -1 }; 17 int sy[] = { 1, -1, 0, 0 }; 18 19 20 struct node 21 { 22 int x, y; 23 int t; 24 }; 25 26 void bfs1() 27 { 28 memset(fire, -1, sizeof(fire)); 29 queue<node> Q; 30 for (int i = 0; i < n;i++) 31 for (int j = 0; j < m; j++) 32 { 33 if (map[i][j] == -1) 34 { 35 node p; 36 p.x = i; 37 p.y = j; 38 p.t = 1; 39 Q.push(p); 40 fire[i][j] = 1; 41 } 42 } 43 while (!Q.empty()) 44 { 45 node p = Q.front(); 46 Q.pop(); 47 for (int k = 0; k < 4; k++) 48 { 49 int x = p.x + sx[k]; 50 int y = p.y + sy[k]; 51 if (x < 0 || x >= n || y < 0 || y >= m) continue; 52 if (map[x][y] != 1) continue; 53 if (fire[x][y] != -1) continue; 54 fire[x][y] = p.t + 1; 55 node u; 56 u.x = x; 57 u.y = y; 58 u.t = p.t + 1; 59 Q.push(u); 60 } 61 } 62 } 63 64 65 int bfs2() 66 { 67 memset(vis, 0, sizeof(vis)); 68 queue<node> Q; 69 node p; 70 p.x = dx; 71 p.y = dy; 72 p.t = 1; 73 Q.push(p); 74 vis[dx][dy] = 1; 75 while (!Q.empty()) 76 { 77 node p = Q.front(); 78 Q.pop(); 79 if (p.x == 0 || p.x == n - 1 || p.y == 0 || p.y == m - 1) return p.t; 80 for (int k = 0; k < 4; k++) 81 { 82 int x = p.x + sx[k]; 83 int y = p.y + sy[k]; 84 if (vis[x][y]) continue; 85 if (x < 0 || x >= n || y < 0 || y >= m) continue; 86 if (map[x][y] != 1) continue; 87 if (fire[x][y]!=-1 && p.t + 1 >= fire[x][y]) continue; 88 node u; 89 u.x = x; 90 u.y = y; 91 u.t = p.t + 1; 92 Q.push(u); 93 vis[x][y] = 1; 94 } 95 } 96 return -1; 97 } 98 99 100 int main() 101 { 102 ios::sync_with_stdio(false); 103 //freopen("D:\txt.txt", "r", stdin); 104 int T; 105 char c; 106 cin >> T; 107 while (T--) 108 { 109 cin >> n >> m; 110 for (int i = 0; i < n;i++) 111 for (int j = 0; j < m; j++) 112 { 113 cin >> c; 114 if (c == '#') map[i][j] = 0; 115 else if (c == 'F') map[i][j] = -1; 116 else if (c == 'J') 117 { 118 map[i][j] = 1; 119 dx = i; 120 dy = j; 121 } 122 else map[i][j] = 1; 123 } 124 125 bfs1(); 126 int ans=bfs2(); 127 if (ans == -1) cout << "IMPOSSIBLE" << endl; 128 else cout << ans << endl; 129 } 130 }