# GitBook

```Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a fire escape plan. Help Joe escape the maze. Given Joe’s location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it. Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.

Input

The first line of input contains a single integer, the number of test cases to follow. The first line of each test case contains the two integers R and C, separated by spaces, with 1 ≤ R, C ≤ 1000. The following R lines of the test case each contain one row of the maze. Each of these lines contains exactly C characters, and each of these characters is one of:

#  a wall
.  a passable square
J  Joe’s initial position in the maze, which is a passable square
F  a square that is on fire There will be exactly one J in each test case.

Output

For each test case, output a single line containing ‘IMPOSSIBLE’ if Joe cannot exit the maze before the fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.

Sample Input

2
4 4
####
#JF#
#..#
#..#
3 3
###
#J.
#.F

Sample Output

3
IMPOSSIBLE

（节点中加入一个是否是火节点的判断，就可以两种节点按不同的细节处理）

#include<stdio.h>
#include<queue>
using namespace std;
char map[1200][1200];
int cnt[1200][1200];
int tmove[4]= {1,-1,0,0};
int inf=99999999;
struct node {
int n,m;
} a[1020*1020];
int x;
int H,W;
int bfs(int n,int m) {
queue<node>q;
node t;
for(int i=0; i<x; i++) {
t.n=a[i].n,t.m=a[i].m;
q.push(t);
}
t.n=n,t.m=m;
q.push(t);
while(!q.empty()) {
t=q.front();
if(map[t.n][t.m]=='F') {
for(int i=0; i<4; i++) {
int tn=t.n+tmove[i],tm=t.m+tmove[(i+2)%4];
if(tn>=0&&tn<H&&tm>=0&&tm<W&&map[tn][tm]=='.') {
map[tn][tm]='F';
node temp;
temp.n=tn,temp.m=tm;
q.push(temp);
}
}
} else {
for(int i=0; i<4; i++) {
int tn=t.n+tmove[i],tm=t.m+tmove[(i+2)%4];
if(tn<0||tn>=H||tm<0||tm>=W)
return cnt[t.n][t.m];
else if(map[tn][tm]=='.'&&cnt[tn][tm]==inf) {
map[tn][tm]='J';
cnt[tn][tm]=cnt[t.n][t.m]+1;
node temp;
temp.n=tn,temp.m=tm;
q.push(temp);
}
}
}
q.pop();
}
return -1;
}
int main() {
int T;
scanf("%d",&T);
while(T--) {
scanf("%d %d",&H,&W);
getchar();
int mH,mW;
x=0;
for(int i=0; i<H; i++) {
for(int j=0; j<W; j++) {
cnt[i][j]=inf;
map[i][j]=getchar();
if(map[i][j]=='F')
a[x].n=i,a[x++].m=j;
else if(map[i][j]=='J')
mH=i,mW=j;
}
getchar();
}
cnt[mH][mW]=1;
int res=bfs(mH,mW);
if(res==-1)
printf("IMPOSSIBLE\n");
else
printf("%d\n",res);
}
return 0;
}