uva11624 - Fire!

链接

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值