Description
Given Joe's location in the maze and which squares of the maze are on fire,you must determine whether Joe can exit the maze before the fire reaches him,and how fast he can do it.
Joe and the fire each move one square per minute, vertically or horizontally (notdiagonally). The fire spreads all four directions from each square that is onfire. Joe may exit the maze from any square that borders the edge of the maze.Neither Joe nor the fire may enter a square that is occupied by a wall.
2 4 4 #### #JF# #..# #..# 3 3 ### #J. #.F
3 IMPOSSIBLE
圖論基礎題。。
AC代碼:
#include#include #include #include #include using namespace std; const int maxn = 1010; int n, m; char g[maxn][maxn]; //用於存儲整個圖 queue > q; //用於bfs的隊列 int a[maxn][maxn]; //用於存儲每個格子開始起火的時間 int move[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; //用於上下左右走 void bfs1() //第一次遍歷,預處理每個格子起火的時間 { memset(a, -1, sizeof(a)); //初始化 while(!q.empty()) q.pop(); //清空隊列 for(int i=0; i tmp = q.front(); q.pop(); int x = tmp.first, y = tmp.second; for(int i=0; i<4; i++) { int t1 = x + move[i][0], t2 = y + move[i][1]; if(a[t1][t2] != -1) continue; if(t1 < 0 || t2 < 0 || t1 >= n || t2 >= m) continue; if(g[t1][t2] == '#') continue; a[t1][t2] = a[x][y] + 1; q.push(make_pair(t1, t2)); } } } int b[maxn][maxn]; int bfs2() //第二次遍歷 { memset(b, -1, sizeof(b)); while(!q.empty()) q.pop(); for(int i=0; i tmp = q.front(); q.pop(); int x = tmp.first, y = tmp.second; if(x == 0 || y == 0 || x == n - 1 || y == m - 1) return b[x][y] + 1; for(int i=0; i<4; i++) { int t1 = x + move[i][0], t2 = y + move[i][1]; if(t1<0 || t2<0 || t1>=n || t2>=m)continue; if(b[t1][t2]!=-1)continue; if(g[t1][t2]=='#')continue; if(a[t1][t2] != -1 && b[x][y] + 1 >= a[t1][t2]) continue; b[t1][t2] = b[x][y] + 1; q.push(make_pair(t1, t2)); } } return -1; //沒有路可走出去 } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d %d", &n, &m); for(int i=0; i