搜索,两次BFS,第一遍BFS处理出火烧的时间,第二次BFS逃跑路线,注意不只有一处火。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1005;
const int inf=0x3f3f3f3f;
struct point
{
int x,y;
};
int fire[maxn][maxn],n,m;
char gra[maxn][maxn];
int pos[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
bool check(int x,int y)
{
if(x>=1&&x<=n&&y<=m&&y>=1) return 1;
else return 0;
}
void bfs1(int x,int y)
{
fire[x][y]=1;
point u;
u.x=x,u.y=y;
queue<point>q;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0;i<4;i++)
{
point v;
v.x=u.x+pos[i][0],v.y=u.y+pos[i][1];
if(fire[u.x][u.y]+1<fire[v.x][v.y]&&check(v.x,v.y)&&gra[v.x][v.y]!='#')
{
q.push(v);
fire[v.x][v.y]=fire[u.x][u.y]+1;
}
}
}
}
int path[maxn][maxn];
int bfs2(int x,int y)
{
path[x][y]=1;
point u;
u.x=x,u.y=y;
queue<point>q;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0;i<4;i++)
{
point v;
v.x=u.x+pos[i][0],v.y=u.y+pos[i][1];
if(!check(v.x,v.y)) return path[u.x][u.y];
if(!path[v.x][v.y]&&gra[v.x][v.y]!='#'&&check(v.x,v.y))
{
path[v.x][v.y]=path[u.x][u.y]+1;
if(path[v.x][v.y]<fire[v.x][v.y])
{
q.push(v);
}
}
}
}
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t;
point s,e;
scanf("%d",&t);
while(t--)
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) fire[i][j]=inf;
queue<point>q;
memset(gra,0,sizeof(gra));
memset(path,0,sizeof(path));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>gra[i][j];
if(gra[i][j]=='F')
{
s.x=i,s.y=j;
q.push(s);
}
if(gra[i][j]=='J') e.x=i,e.y=j;
}
}
while(!q.empty())
{
s=q.front();
q.pop();
bfs1(s.x,s.y);
}
int ans=bfs2(e.x,e.y);
if(ans==-1) printf("IMPOSSIBLE\n");
else printf("%d\n",ans);
}
return 0;
}