造福千秋
2024-02-03 11:13:57
发布于:浙江
19阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int a[1009][1009];
struct node{
    int x,y,step;
}l,r;
int dir[4][2]={-1,0,0,1,1,0,0,-1};
int main(){
    int n,m;
    cin>>n>>m;
    queue<node> q;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>a[i][j];
            if(a[i][j]==2) q.push({i,j,0});
        }
    }
    int ans=0;
    while(q.size()){
        r = q.front();
        q.pop();
        ans=max(ans,r.step);
        for(int i=0;i<4;i++){
            l.x=r.x+dir[i][0],l.y=r.y+dir[i][1],l.step=r.step+1;
            if(l.x>=1&&l.x<=n&&l.y>=1&&l.y<=m&&a[l.x][l.y]==1){
                a[l.x][l.y]=2;
                q.push(l);
            }
        }
    }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(a[i][j]==1) ans=-1;
            }
        }
        cout<<ans;
        return 0;
    }
这里空空如也

有帮助,赞一个