1 条题解

  • 1
    @ 2021-8-7 21:05:13

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    typedef pair<int,int> pll;
    const int maxn=1e3+5;
    int n,m,d[maxn][maxn];
    char g[maxn][maxn];
    void bfs() {
    	memset(d,-1,sizeof d);
    	queue<pll>q;
    	for(int i=0; i<n; i++) {
    		for(int j=0; j<m; j++) {
    			if(g[i][j]=='1') {
    				q.push({i,j});
    				d[i][j]=0;
    			}
    		}
    	}
    
    	int dx[4]= {-1,0,1,0},dy[4]= {0,-1,0,1};
    	while(q.size()) {
    		pll t=q.front();
    		q.pop();
    		for(int i=0; i<4; i++) {
    			int x=t.first+dx[i];
    			int y=t.second+dy[i];
    			if(x>=0&&x<n&&y>=0&&y<m&&d[x][y]==-1) {
    				d[x][y]=d[t.first][t.second]+1;
    				q.push({x,y});
    			}
    		}
    	}
    }
    int main() {
    	ios::sync_with_stdio(false);
    	cin.tie(0);
    	cin>>n>>m;
    	for(int i=0; i<n; i++) cin>>g[i];
    	bfs();
    	for(int i=0; i<n; i++) {
    		for(int j=0; j<m; j++) {
    			if(j) cout<<" ";
    			cout<<d[i][j];
    		}
    		cout<<endl;
    	}
    	return 0;
    }
    
    • 1

    信息

    ID
    84
    时间
    1000ms
    内存
    128MiB
    难度
    1
    标签
    递交数
    31
    已通过
    31
    上传者