链接
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671
题解
一开始先把所有的火都放进去进行一次
b
f
s
bfs
bfs,求出每个格子最早着火的时间
然后再以人为起点做
b
f
s
bfs
bfs,如果到达这个点的最小时间大于最早着火时间,就能走过去。求出到每个点的最短时间,这题就结束了
代码
#include <bits/stdc++.h>
#define maxn 1010
#define iinf 0x3f3f3f3f
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
char mp[maxn][maxn];
int on_fire[maxn][maxn], dx[4]{0,1,0,-1}, dy[4]={1,0,-1,0}, vis[maxn][maxn], R, C, dis[maxn][maxn];
bool ok(pair<int,int> p)
{
if(p.first<1 or p.first>R)return false;
if(p.second<1 or p.second>C)return false;
if(mp[p.first][p.second]=='#')return false;
return true;
}
void bfs1()
{
int i, j;
queue<pair<int,int>> q;
for(i=1;i<=R;i++)for(j=1;j<=C;j++)vis[i][j]=0, on_fire[i][j]=iinf;
for(i=1;i<=R;i++)for(j=1;j<=C;j++)
if(mp[i][j]=='F')q.emplace( make_pair(i,j) ), vis[i][j]=1, on_fire[i][j]=0;
while(!q.empty())
{
auto now=q.front(); q.pop();
for(auto d(0);d<4;d++)
{
auto to=make_pair(now.first+dx[d],now.second+dy[d]);
if(ok(to) and !vis[to.first][to.second])
{
vis[to.first][to.second]=1;
on_fire[to.first][to.second]=on_fire[now.first][now.second]+1;
q.emplace(to);
}
}
}
}
int bfs2()
{
int i, j;
queue<pair<int,int>> q;
for(i=1;i<=R;i++)for(j=1;j<=C;j++)vis[i][j]=dis[i][j]=0;
for(i=1;i<=R;i++)for(j=1;j<=C;j++)if(mp[i][j]=='J')q.emplace( make_pair(i,j) ), vis[i][j]=1;
while(!q.empty())
{
auto now=q.front(); q.pop();
if(now.first==1 or now.first==R or now.second==1 or now.second==C)return dis[now.first][now.second];
for(auto d(0);d<4;d++)
{
auto to=make_pair(now.first+dx[d],now.second+dy[d]);
if(ok(to) and !vis[to.first][to.second] and dis[now.first][now.second]+1<on_fire[to.first][to.second])
{
vis[to.first][to.second] = 1;
dis[to.first][to.second] = dis[now.first][now.second]+1;
q.emplace(to);
}
}
}
return -1;
}
int read(int x=0)
{
int c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-48;
return f*x;
}
int main()
{
auto T(read());
while(T--)
{
R=read(), C=read();
for(auto i=1;i<=R;i++)scanf("%s",mp[i]+1);
bfs1();
auto ans=bfs2();
if(ans==-1)printf("IMPOSSIBLE\n");
else printf("%d\n",ans+1);
}
return 0;
}