BFS, a slightly complex BFs, separate the fire and the person's location BFS (first fire and then people) until the person reaches the border or is surrounded by fire and no way to go.
CodeAs follows:
# Include <cstdio> # include <cstring> const int maxn = 1001; struct point {int X, Y, mem_step; bool bool_fire; // identify whether it is 'fire'} que [maxn * maxn]; int R, C, FX, FY; int step_x [4] = {1,-, 0 }; int step_y [4] = {0, 1,-1}; char image [maxn] [maxn]; bool vis [maxn] [maxn]; int BFS () {int font = 0, rear = 0; memset (VIS, false, sizeof (VIS); For (INT I = 0; I <r; I ++) for (Int J = 0; j <C; j ++) // enter the queue with 'fire' (Note: there are more than one initial position 'fire ') if (image [I] [J] = 'F') {que [rear]. X = J; que [rear]. y = I; que [rear]. mem_step = 0; que [rear]. bool_fire = true; ++ rear;} que [rear]. X = FX; // 'Personal' enters the queue que [rear]. y = FY; que [rear]. mem_step = 0; que [rear ++]. bool_fire = false; while (font <rear) {int xx = que [font]. x; int YY = que [font]. y; If (que [font]. bool_fire) // extended 'fire' {for (INT I = 0; I <4; I ++) {xx = que [font]. X + step_x [I]; YY = que [font]. Y + step_y [I]; if (XX <0 | XX> = c | YY <0 | YY> = r | image [YY] [XX] = '#' | image [YY] [XX] = 'F ') continue; image [YY] [XX] = 'F'; que [rear]. X = xx; que [rear]. y = YY; que [rear]. bool_fire = true; que [rear]. mem_step = que [font]. mem_step + 1; ++ rear ;}} else {for (INT I = 0; I <4; I ++) // extended 'people' {int xx = que [font]. X + step_x [I]; int YY = que [font]. Y + step_y [I]; if (vis [YY] [XX] | image [YY] [XX] = '#' | image [YY] [XX] = 'F') continue; if (XX <0 | XX> = c | YY <0 | YY> = r) return que [font]. mem_step + 1; vis [YY] [XX] = true; que [rear]. X = xx; que [rear]. y = YY; que [rear]. bool_fire = false; que [rear]. mem_step = que [font]. mem_step + 1; ++ rear ;}++ font ;}return 0 ;}int main () {# ifdef test freopen ("sample.txt", "r", stdin ); # endif int T, flag; scanf ("% d", & T); While (t --) {scanf ("% d", & R, & C ); FX = FY =-1; for (INT I = 0; I <r; I ++) {scanf ("% s", image [I]); if (FX =-1) for (Int J = 0; j <C; j ++) if (image [I] [J] = 'J ') {FX = J; FY = I; break ;}} flag = BFS (); If (FLAG) printf ("% d \ n", flag ); else printf ("impossible \ n");} return 0 ;}