Problem: http://acm.hust.edu.cn: 8080/judge/problem/viewproblem. Action? Id = 28833
Basic Search, pre-processing the time when each grid fires. Then, BFs is used for humans.
# Include <cstdio> # include <cstring> # include <queue> using namespace STD; typedef pair <int, int> TP; const int INF = 0x3f3f3f; const int n = 1111; char s [N] [N]; int DX [4] = {,-}; int dy [4] = {, 0,-1}; int t, n, m, Lim [N] [N], DIS [N] [N]; void Init () {queue <TP> q; memset (Lim, 63, sizeof (lim); For (INT I = 0; I <n; I ++) for (Int J = 0; j <m; j ++) if (s [I] [J] = 'F') Q. push (TP (I, j), Lim [I] [J] = 0; while (! Q. empty () {TP u = Q. front (); q. pop (); For (INT I = 0; I <4; I ++) {int x = u. first + dx [I], y = u. second + dy [I]; If (x <0 | Y <0 | x = n | Y = M | Lim [x] [Y]! = Inf | s [x] [Y] = '#') continue; Lim [x] [Y] = lim [U. first] [U. second] + 1; q. push (TP (x, y) ;}} int BFS () {queue <TP> q; memset (DIS, 63, sizeof (DIS )); for (INT I = 0; I <n; I ++) for (Int J = 0; j <m; j ++) if (s [I] [J] = 'J') Q. push (TP (I, j), DIS [I] [J] = 0; while (! Q. empty () {TP u = Q. front (); q. pop (); For (INT I = 0; I <4; I ++) {int x = u. first + dx [I], y = u. second + dy [I], D = dis [U. first] [U. second]; If (x <0 | Y <0 | x = n | Y = m) return D + 1; if (DIS [x] [Y]! = Inf | D + 1> = lim [x] [Y] | s [x] [Y] = '#') continue; dis [x] [Y] = d + 1; q. push (TP (x, y) ;}} return-1 ;}int main () {scanf ("% d", & T); While (t --) {scanf ("% d", & N, & M); For (INT I = 0; I <n; I ++) scanf ("% s ", s [I]); Init (); int ans = BFS (); If (ANS =-1) puts ("impossible "); else printf ("% d \ n", ANS);} return 0 ;}