一次BFS就可以,火先走,人后走
#include<iostream>
#include<cstring>
#include<queue>
#include<string>
#include<climits>
#include<map>
#include<algorithm>
using namespace std;
const int N = 1010;
struct Cell{
int x,y,o;
}J,tc;
int g[N][N],st[N][N];
queue<Cell> q;
int n,m;
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
int flag;
void bfs(){
while(!q.empty()){
Cell t=q.front();q.pop();
if(t.o==0&&(t.x==0||t.x==n-1||t.y==0||t.y==m-1)){
cout<<st[t.x][t.y]+1<<endl;
flag=1;
return;
}
for(int k=0;k<4;k++){
int xx=t.x+dx[k],yy=t.y+dy[k];
Cell tt={xx,yy,t.o};
if(xx>=0&&xx<n&&yy>=0&&yy<m&&g[xx][yy]==0){
if(t.o==1){
g[xx][yy]=1;
q.push(tt);
}
else
if(!~st[xx][yy]){
st[xx][yy]=st[t.x][t.y]+1;
q.push(tt);
}
}
}
}
}
int main(){
int T;cin>>T;
while(T--){
memset(st,-1,sizeof st);
memset(g,0,sizeof g);
while(!q.empty())q.pop();
flag=0;
cin>>n>>m;
for(int i=0;i<n;i++){
string str;cin>>str;
for(int j=0;j<m;j++){
if(str[j]=='J'){
st[i][j]=0;
J={i,j,0};
}
else if(str[j]=='F'){
tc={i,j,1};
q.push(tc);
g[i][j]=1;
}else if(str[j]=='#')g[i][j]=1;
}
}q.push(J);
bfs();
if(!flag)
cout<<"IMPOSSIBLE"<<endl;
/*
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
cout<<g[i][j];
cout<<endl;
}*/
}
}