The minimum fire time of each point is obtained after a BFS fire is first performed.
The minimum time for reaching the boundary is obtained again for the human BFS.
# Include <iostream> # include <queue> # include <cstring> using namespace std; int n, m, bz [1005] [1005], qihuo [1005] [1005]; char map [1005] [1005]; int h [4] [2] = {-, 0,-, 1}; struct point {int x, y, step ;}; queue <point> q; void bfs_huo () {int I, j, x, y; point t, tt; while (! Q. empty () {t = q. front (); q. pop (); for (I = 0; I <4; I ++) {x = t. x + h [I] [0]; y = t. y + h [I] [1]; if (x> = 0 & x <n & y> = 0 & y <m & (map [x] [y] = '. '| map [x] [y] = 'J ')&&! Bz [x] [y]) {bz [x] [y] = 1; tt. x = x; tt. y = y; tt. step = t. step + 1; qihuo [x] [y] = tt. step; q. push (tt) ;}}} int bfs_men (point s) {int I, j, x, y; point t, tt; while (! Q. empty () q. pop (); q. push (s); bz [s. x] [s. y] = 1; while (! Q. empty () {t = q. front (); q. pop (); if (t. x <= 0 | t. * = n-1 | t. y <= 0 | t. y = s-1) return t. step ;//?? Why? 0 for (I = 0; I <4; I ++) {x = t. x + h [I] [0]; y = t. y + h [I] [1]; if (x> = 0 & x <n & y> = 0 & y <m & (map [x] [y] = '. '| map [x] [y] = 'J ')&&! Bz [x] [y]) {if (qihuo [x] [y] <= t. step + 1) continue; bz [x] [y] = 1; tt. x = x; tt. y = y; tt. step = t. step + 1; q. push (tt) ;}} return-1;} int main (int argc, char * argv []) {int nn, I, j; point s, t; cin> nn; while (nn --) {cin> n> m; while (! Q. empty () q. pop (); memset (bz, 0, sizeof (bz); for (I = 0; I <n; I ++) for (j = 0; j <m; j ++) {cin> map [I] [j]; qihuo [I] [j] = 1000000000 ;//??? If (map [I] [j] = 'J') {s. x = I; s. y = j; s. step = 0;} if (map [I] [j] = 'F') {t. x = I; t. y = j; t. step = 0; q. push (t); bz [I] [j] = 1; qihuo [I] [j] = 0 ;}} bfs_huo (); memset (bz, 0, sizeof (bz); int ans = bfs_men (s); if (ans> = 0) cout <ans + 1 <endl; else cout <"IMPOSSIBLE" <endl;} return 0 ;}