1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <bits/stdc++.h> using namespace std; const int N = 1005; int x[] = {0, 0, -1, 1}; int y[] = { -1, 1, 0, 0}; int v[N][N], n, m, ans, le, ri; pair<int, int> q[N * N]; char g[N][N];
void bfs() { int cr, cc, r, c; while(le < ri) { cr = q[le].first, cc = q[le++].second; for(int i = 0; i < 4; ++i) { r = cr + x[i], c = cc + y[i]; if(r < 0 || r >= n || c < 0 || c >= m) ans = ans ? ans : v[cr][cc]; else if(g[r][c] == '.' && (!v[r][c] || v[cr][cc] + 1 < v[r][c])) v[r][c] = v[cr][cc] + 1, q[ri++] = make_pair(r, c); } } }
int main() { int cas, jr, jc; scanf("%d", &cas); while(cas--) { scanf("%d%d", &n, &m); for(int i = 0; i < n; ++i) scanf("%s", g[i]);
memset(v, 0, sizeof(v)); le = ri = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) if(g[i][j] == 'F') q[ri++] = make_pair(i, j), v[i][j] = 1; else if(g[i][j] == 'J') jr = i, jc = j; bfs(); le = ri = ans = 0, v[jr][jc] = 1; q[ri++] = make_pair(jr, jc); bfs(); if(ans) printf("%d\n", ans); else puts("IMPOSSIBLE"); } return 0; }
|