# kuangbin专题一 简单搜索 J - Fire!

## J - Fire!

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int _max=1200;
const int _m=999999;
struct node{
int x,y;
int t;
};
int T,n,m,jx,jy,stepfire[_max][_max],scount;
int dirx[]={1,-1,0,0},diry[]={0,0,1,-1};
bool vis[_max][_max];
char mp[_max][_max];
bool check(node p){
if(p.x>n||p.x<1||p.y>m||p.y<1) return false;
if(!vis[p.x][p.y]) return false;
if(mp[p.x][p.y]=='#') return false;
return true;
}
queue<node>f;
void firebfs(){
node now,next;
while(!f.empty()){
now=f.front();
f.pop();
for(int i=0;i<4;i++){
next.x=now.x+dirx[i];
next.y=now.y+diry[i];
next.t=now.t+1;
if(!check(next)) continue;
vis[next.x][next.y]=0;
stepfire[next.x][next.y]=min(next.t,stepfire[next.x][next.y]);
f.push(next);
}
}
}
void bfs(int sx,int sy){
queue<node> q;
node now,next;
now.x=sx;
now.y=sy;
now.t=0;
vis[sx][sy]=0;
q.push(now);
while(!q.empty()){
now=q.front();
q.pop();
if(now.x==1||now.x==n||now.y==1||now.y==m){
scount=min(scount,now.t+1);
}
for(int i=0;i<4;i++){
next.x=now.x+dirx[i];
next.y=now.y+diry[i];
next.t=now.t+1;
if((!check(next))||(next.t>stepfire[next.x][next.y])||next.t==stepfire[next.x][next.y]) continue;
vis[next.x][next.y]=0;
q.push(next);
}
}
}
int main()
{
cin>>T;
while(T--){
cin>>n>>m;
scount=_m;
memset(stepfire,_m,sizeof(stepfire));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
cin>>mp[i][j];
if(mp[i][j]=='F'){
node fire;
fire.x=i;
fire.y=j;
fire.t=0;
stepfire[i][j]=1;
f.push(fire);
}
if(mp[i][j]=='J'){
jx=i;jy=j;
}
}
memset(vis,1,sizeof(vis));
firebfs();
memset(vis,1,sizeof(vis));
bfs(jx,jy);
if(scount==_m)
cout<<"IMPOSSIBLE"<<endl;
else
cout<<scount<<endl;
}

}