3 条题解

  • 0
    @ 2026-5-15 22:26:57

    先用bfs跑一遍火和人走到每一格的最短时间 最后再找人能走到而且火没跑到的最短边缘 AC代码:

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int N=1010;
    struct node {
        int x;int y;
    };
    char mp[N][N];
    int f[N][N];
    int q[N][N];
    int xlj[4]={1,-1,0,0};
    int ylj[4]={0,0,1,-1};
    int n;int m;
    void bfs(int st[N][N],queue<node>&qqq) {
        while (!qqq.empty()) {
            node t=qqq.front();qqq.pop();
            for (int i=0;i<4;i++) {
                int x=t.x+xlj[i];
                int y=t.y+ylj[i];
                if (mp[x][y]=='#')continue;
                if (st[x][y]!=-1)continue;
                if (x<1||x>n||y<1||y>m)continue;
                qqq.push({x,y});
                st[x][y]=st[t.x][t.y]+1;
            }
        }
    }
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        cin>>n>>m;
        queue<node>fq;
        queue<node>qq;
        for (int i=1;i<=n;i++) {
            string s;cin>>s;
            for (int j=1;j<=m;j++) {
                mp[i][j]=s[j-1];
                f[i][j]=-1;
                q[i][j]=-1;
                if (mp[i][j]=='F') {
                    fq.push({i,j});
                    f[i][j]=0;
                }
                if (mp[i][j]=='J') {
                    qq.push({i,j});
                    q[i][j]=0;
                }
            }
        }
        bfs(q,qq);
        bfs(f,fq);
        for (int i=1;i<=n;i++)qq.push({i,1});
        for (int i=1;i<=m;i++)qq.push({1,i});
        for (int i=1;i<=n;i++)qq.push({i,m});
        for (int i=1;i<=m;i++)qq.push({n,i});
        int ans=INT_MAX;
        while (!qq.empty()) {
            node t=qq.front();qq.pop();
            int x=t.x;int y=t.y;
            if (q[x][y]!=-1&&(q[x][y]<f[x][y]||f[x][y]==-1)) {
                ans=min(q[x][y],ans);
            }
        }
        if (ans==INT_MAX) cout<<"IMPOSSIBLE";
        else cout<<ans+1;
        return 0;
    }
    
    

    信息

    ID
    524
    时间
    1000ms
    内存
    256MiB
    难度
    普及−
    标签
    递交数
    173
    已通过
    40
    上传者