分析:广搜,在加入Joe的起始位置之前,先把所有着火点加入队列。Joe只能到达没有障碍和火势控制的格子。
1 #include <cstdio> 2 #include <cstring> 3 4 const int MAXN = 1004; 5 const int dx[] = { -1, 1, 0, 0 }; 6 const int dy[] = { 0, 0, -1, 1 }; 7 8 struct point 9 { 10 int x, y; 11 int minit; 12 bool fir; 13 }; 14 15 char map[MAXN][MAXN]; 16 bool vis[MAXN][MAXN]; 17 point Q[MAXN * MAXN]; 18 point start; 19 point fire[MAXN * MAXN]; 20 int r, c; 21 int cnt; 22 23 bool check( int x, int y ) 24 { 25 return x > 0 && x <= r && y > 0 && y <= c ; 26 } 27 28 int BFS() 29 { 30 int front = 0, rear = 0; 31 32 for ( int i = 0; i < cnt; ++i ) 33 Q[ rear++ ] = fire[i]; 34 35 Q[ rear++ ] = start; 36 37 while ( front < rear ) 38 { 39 point &tp = Q[front]; 40 41 if ( tp.fir ) 42 { 43 for ( int i = 0; i < 4; ++i ) 44 { 45 int xx = tp.x + dx[i]; 46 int yy = tp.y + dy[i]; 47 if ( check(xx, yy) && ( !vis[xx][yy] ) ) 48 { 49 vis[xx][yy] = true; 50 Q[rear].fir = true; 51 Q[rear].minit = tp.minit + 1; 52 Q[rear].x = xx; 53 Q[rear++].y = yy; 54 } 55 } 56 } 57 else if ( map[ tp.x ][ tp.y ] == 'J' ) 58 { 59 for ( int i = 0; i < 4; ++i ) 60 { 61 int xx = tp.x + dx[i]; 62 int yy = tp.y + dy[i]; 63 if ( !vis[xx][yy] ) 64 { 65 vis[xx][yy] = true; 66 map[xx][yy] = 'J'; 67 Q[rear].fir = false; 68 Q[rear].minit = tp.minit + 1; 69 Q[rear].x = xx; 70 Q[rear].y = yy; 71 if ( !check( xx, yy ) ) return Q[rear].minit; 72 ++rear; 73 } 74 } 75 } 76 77 ++front; 78 } 79 80 return -1; 81 } 82 83 int main() 84 { 85 int T; 86 scanf( "%d", &T ); 87 while ( T-- ) 88 { 89 scanf( "%d%d", &r, &c ); 90 91 cnt = 0; 92 memset( vis, false, sizeof(vis) ); 93 memset( map, '.', sizeof(map) ); 94 95 for ( int i = 1; i <= r; ++i ) 96 { 97 getchar(); 98 for ( int j = 1; j <= c; ++j ) 99 { 100 map[i][j] = getchar(); 101 switch( map[i][j] ) 102 { 103 case 'J': 104 start.x = i; 105 start.y = j; 106 start.minit = 0; 107 start.fir = false; 108 vis[i][j] = true; 109 break; 110 111 case 'F': 112 vis[i][j] = true; 113 fire[cnt].x = i; 114 fire[cnt].y = j; 115 fire[cnt].fir = true; 116 fire[ cnt++ ].minit = 0; 117 break; 118 119 case '#': 120 vis[i][j] = true; 121 break; 122 } 123 } 124 } 125 int ans = BFS(); 126 if ( ans == -1 ) puts("IMPOSSIBLE"); 127 else printf( "%d\n", ans ); 128 } 129 return 0; 130 }