用先让火走的原则,再让人走,运用一个广搜即可,最后步骤不要忘了加一
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int INF=10000000;
const int maxn=1000+100;
int n,m;
char str[maxn][maxn];
int vis[maxn][maxn];
struct node{
int x,y,step;
node(){}
node(int xx,int yy,int ss)
{
x=xx,y=yy,step=ss;
}
};
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
queue<node> q;
int bfs()
{
memset(vis,0,sizeof(vis));
while(!q.empty())
{
node th=q.front();q.pop();
int x=th.x,y=th.y,step=th.step;
if(step!=INF&&(x==0||x==n-1||y==0||y==m-1))
return step;
for(int i=0;i<4;i++)
{
node rh=th;
rh.x+=d[i][0],rh.y+=d[i][1];
int xx=rh.x,yy=rh.y,sstep=rh.step;
if(xx>=0&&xx<n&&yy>=0&&yy<m&&str[xx][yy]=='.')
{
if(sstep==INF)
{
str[xx][yy]='F';
q.push(node(xx,yy,INF));
}
else if(!vis[xx][yy])
{
vis[xx][yy]=1;
q.push((node(xx,yy,step+1)));
}
}
}
}
return -1;
}
int main()
{
int t;
//freopen("J.txt","r",stdin);
scanf("%d",&t);
//cout<<t<<endl;
while(t--)
{
while(!q.empty()) q.pop();
scanf("%d %d",&n,&m);
node star;
int cnt=0;
for(int i=0;i<n;i++)
{
scanf("%s",&str[i]);
for(int j=0;str[i][j];j++)
{
if(str[i][j]=='J')
{
star.x=i,star.y=j,star.step=0;
}
if(str[i][j]=='F')
{
cnt++;
q.push(node(i,j,INF));
}
}
}
q.push(star);
int tmp=bfs();
if(tmp==-1) printf("IMPOSSIBLE\n");
else printf("%d\n",tmp+1);
}
}