逐渐唤醒被寒假尘封的搜索知识!
题目大意:JAKE跟一团火呆在一个迷宫里,注意火每分钟会向四个方向同时蔓延,问JAKE能否及时逃出去,我们假设只要JAKE走到边缘就算已经走出。
思路:稍微带一点技巧性的BFS,首先我们BFS跑一遍火的时间,然后再跑一边JAKE的时间两者进行比对,得出最后结果。
下面给出AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000+100;
const int INF=0x3f3f3f3f;
struct node
{
int x,y;
};
int m,n;
char c[maxn][maxn];
int st1[maxn][maxn],st2[maxn][maxn];
bool used[maxn][maxn];
int idx[4]= {1,0,-1,0};
int idy[4]= {0,1,0,-1};
void BFS_Fire(int st[][maxn],node post)
{
queue<node> que;
que.push(post);
used[post.x][post.y]=true;
st[post.x][post.y]=0;
while(!que.empty())
{
node pos=que.front();
que.pop();
for(int i=0; i<4; i++)
{
int nx=pos.x+idx[i];
int ny=pos.y+idy[i];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&!used[nx][ny]&&c[nx][ny]!='#'&&st[nx][ny]>=(st[pos.x][pos.y]+1))
{
st[nx][ny]=st[pos.x][pos.y]+1;
used[nx][ny]=true;
que.push(node{nx,ny});
}
}
}
}
void BFS_J(int st[][maxn],node post)
{
queue<node> que;
que.push(post);
used[post.x][post.y]=true;
st[post.x][post.y]=0;
while(!que.empty())
{
node pos=que.front();
que.pop();
for(int i=0; i<4; i++)
{
int nx=pos.x+idx[i];
int ny=pos.y+idy[i];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&!used[nx][ny]&&c[nx][ny]!='#'&&st[pos.x][pos.y]+1<st2[nx][ny])
{
st[nx][ny]=st[pos.x][pos.y]+1;
used[nx][ny]=true;
que.push(node{nx,ny});
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(st1,INF,sizeof(st1));
memset(st2,INF,sizeof(st2));
memset(used,0,sizeof(used));
node st;
scanf("%d %d",&n,&m);
for(int i=0; i<n; i++)
{
scanf("%s",c[i]);
for(int j=0; j<m; j++)
{
if(c[i][j]=='J')
{
st.x=i;
st.y=j;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(c[i][j]=='F')
{
memset(used,0,sizeof(used));
BFS_Fire(st2,node{i,j});
}
}
}
memset(used,0,sizeof(used));
BFS_J(st1,st);
int flag=1,cnt=INF;
for(int i=0;i<m;i++)
{
if(st1[0][i]!=INF)
{
flag=0;
cnt=min(st1[0][i],cnt);
}
}
for(int i=0;i<m;i++)
{
if(st1[n-1][i]!=INF)
{
flag=0;
cnt=min(st1[n-1][i],cnt);
}
}
for(int i=0;i<n;i++)
{
if(st1[i][0]!=INF)
{
flag=0;
cnt=min(st1[i][0],cnt);
}
}
for(int i=0;i<n;i++)
{
if(st1[i][m-1]!=INF)
{
flag=0;
cnt=min(st1[i][m-1],cnt);
}
}
if(flag) printf("IMPOSSIBLE\n");
else printf("%d\n",cnt+1);
}
return 0;
}