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 53 54 55 56 57 58 59 60 61 62 63 64
| #include <bits/stdc++.h> using namespace std;
const int N = 1e3+66;
int n, m, T; int vis[N][N]; char ch[N][N];
int dx[5] = {0, 0, 1, -1}; int dy[5] = {1, -1, 0, 0};
struct node {int x, y;node(int x, int y):x(x), y(y){}};
inline void bfs () { queue<node>jq, fq; for (int i = 0; i < n; ++ i) for (int j = 0; j < m; ++ j) { if (ch[i][j] == 'J') { jq.push(node(i, j)); vis[i][j] = 1; } else if (ch[i][j] == 'F') { fq.push(node(i, j)); ch[i][j] = '#'; } } int step(0); while (jq.size()) { ++ step; for (int i = 0, j = jq.size(); i < j; ++ i) { node tmp = jq.front(); jq.pop(); if (ch[tmp.x][tmp.y] == '#') continue; for (int k = 0; k < 4; ++ k) { int nx = tmp.x+dx[k], ny = tmp.y+dy[k]; if (nx >= 0 && nx < n && ny >= 0 && ny < m) { if (ch[nx][ny] != '#' && !vis[nx][ny]) vis[nx][ny] = 1, jq.push(node(nx, ny)); } else {cout << step << '\n'; return;} } } for (int i = 0, j = fq.size(); i < j; ++ i) { node tmp = fq.front(); fq.pop(); for (int k = 0; k < 4; ++ k) { int nx = tmp.x+dx[k], ny = tmp.y+dy[k]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && ch[nx][ny] != '#') ch[nx][ny] = '#', fq.push(node(nx, ny)); } } } puts ("IMPOSSIBLE"); }
int main () { cin >> T; while (T --> 0) { cin >> n >> m; for (int i = 0; i < n; ++ i) scanf ("%s", ch[i]); bfs (); memset (vis, 0, sizeof vis); } return 0; }
|