1 #include<stdio.h> 2 #include<string.h> 3 const int N = 1010; 4 char map[N][N]; 5 int time[N][N]; 6 bool v[N][N]; 7 struct node { 8 int x, y, minute; 9 }q[N * N], joe, fire, cur, next; 10 int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1}, r, c; 11 bool judge(node cur) {//边界判断 12 if(cur.x >= 0 && cur.x < r && cur.y >= 0 && cur.y < c) 13 return true; 14 else 15 return false; 16 } 17 void bfs1() { //预处理着火时间 18 int front = 0, rear = -1; 19 memset(time, -1 , sizeof(time)); 20 for(int i = 0; i < r; ++i) { 21 for(int j = 0; j < c; ++j) { 22 if(map[i][j] == 'F') { 23 cur.x = i; cur.y = j; cur.minute = 0; 24 q[++rear] = cur; 25 } 26 } 27 } 28 memset(v, 0, sizeof(v)); 29 while(front <= rear) { 30 cur = q[front++]; 31 for(int i = 0; i < 4; ++i) { 32 next.x = cur.x + dir[i][0]; 33 next.y = cur.y + dir[i][1]; 34 next.minute = cur.minute + 1; 35 if(judge(next) && map[next.x][next.y] == '.' && !v[next.x][next.y]) { 36 v[next.x][next.y] = 1; 37 time[next.x][next.y] = next.minute; 38 q[++rear] = next; 39 } 40 } 41 } 42 } 43 int bfs2(node start) { 44 int front = 0, rear = -1; 45 q[++rear] = start; 46 while(front <= rear) { 47 cur = q[front++]; 48 if(cur.x == 0 || cur .x == r - 1 || cur.y == 0 || cur.y == c - 1) { 49 return cur.minute + 1; 50 } 51 for(int i = 0; i < 4; ++i) { 52 next.x = cur.x + dir[i][0]; 53 next.y = cur.y + dir[i][1]; 54 next.minute = cur. minute + 1; 55 if(judge(next) && map[next.x][next.y] == '.' 56 && (time[next.x][next.y] == -1 || next.minute < time[next.x][next.y])) { 57 map[next.x][next.y] = '#'; 58 q[++rear] = next; 59 } 60 } 61 } 62 return -1; 63 } 64 int main() { 65 int t, i, j; 66 scanf("%d", &t); 67 while(t--) { 68 scanf("%d%d", &r, &c); 69 for(i = 0; i < r; ++i) { 70 scanf("%s", map[i]); 71 for(j = 0; j < c; ++j) { 72 if(map[i][j] == 'J') { 73 joe.x = i; 74 joe.y = j; 75 joe.minute = 0; 76 } 77 } 78 } 79 bfs1(); 80 int ans = bfs2(joe); 81 if(ans == -1) 82 printf("IMPOSSIBLE\n"); 83 else 84 printf("%d\n", ans); 85 } 86 return 0; 87 }
浙公网安备 33010602011771号