混合的BFS。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int dir_x[4]={1,-1,0,0};
int dir_y[4]={0,0,1,-1};
struct node
{
int x,y,f,t;
};
char MP[1200][1200];
bool vis[1200][1200];
int T,n,m;
bool isINSIDE(node a)
{
if((a.x>=0&&a.x<n)&&(a.y>=0&&a.y<m)) return true;
return false;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",MP+i);
queue<node> q;
node Joe;
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(MP[i][j]=='#')
{
vis[i][j]=1;
}
else if(MP[i][j]=='F')
{
vis[i][j]=1;
q.push((node){i,j,1,0});
}
else if(MP[i][j]=='J')
{
vis[i][j]=1;
Joe.x=i;Joe.y=j;Joe.f=0;Joe.t=0;
}
}
}
q.push(Joe);
int ans=-1;
while(!q.empty())
{
node u,v;
u=q.front(); q.pop();
for(int i=0;i<4;i++)
{
v=u;
v.t++;
v.x+=dir_x[i],v.y+=dir_y[i];
if(isINSIDE(v))
{
if(vis[v.x][v.y]) continue;
vis[v.x][v.y]=1;
q.push(v);
}
else if(v.f==0)
{
ans=v.t;
break;
}
}
if(ans!=-1) break;
}
if(ans==-1) puts("IMPOSSIBLE");
else printf("%d\n",ans);
}
return 0;
}