AcWing 173. 矩阵距离
原题链接
简单
作者:
minux
,
2020-05-21 16:05:59
,
所有人可见
,
阅读 735
c++ 多源bfs
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define fi first
#define se second
const int N=1005;
const int dirs[4][2]={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int n, m;
char G[N][N];
int dist[N][N];
int main(){
memset(dist, -1, sizeof dist);
memset(G, 0x00, sizeof G);
queue<PII> q;
cin>>n>>m;
for(int i=0; i<n; ++i){
for(int j=0; j<m; ++j){
cin>>G[i][j];
if(G[i][j]=='1') {
q.push({i, j});
dist[i][j]=0;
}
}
}
while(!q.empty()){
int x=q.front().fi;
int y=q.front().se;
q.pop();
for(int i=0; i<4; ++i){
int nx=x+dirs[i][0];
int ny=y+dirs[i][1];
if(0<=nx && nx<n && 0<=ny && ny<m && dist[nx][ny]==-1 && G[nx][ny]=='0'){
dist[nx][ny]=dist[x][y]+1;
q.push({nx, ny});
}
}
}
for(int i=0; i<n; ++i){
for(int j=0; j<m; ++j){
cout<<dist[i][j]<<" ";
}
cout<<endl;
}
return 0;
}