https://hydro.ac/d/bzoj/p/2252
#include <bits/stdc++.h>
using namespace std;
int n, m;
char mp[1005][1005];
int ans[1005][1005];
const int dx[] = {0, 0, 1, -1};
const int dy[] = {-1, 1, 0, 0};
struct Node {
int x, y, step;
};
queue<Node> q;
void bfs() {
int x; int y; int step;
while (!q.empty()) {
x = q.front().x;
y = q.front().y;
step = q.front().step;
q.pop();
for (int i = 0; i <= 3; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx < 1 || yy < 1 || xx > n || yy > m) {
continue;
}
if (mp[xx][yy] == '1') {
continue;
}
if (step + 1 >= ans[xx][yy]) {
continue;
}
ans[xx][yy] = step + 1;
q.push((Node){xx, yy, step + 1});
}
}
return;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ans[i][j] = INT_MAX;
cin >> mp[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp[i][j] == '1') {
ans[i][j] = 0;
q.push((Node){i, j, 0});
bfs();
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cout << ans[i][j] << " ";
}
cout << "\n";
}
return 0;
}
/*
3 4
0001
0011
0110
*/