矩阵距离
多点BFS
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int d[N][N], g[N][N];
int main()
{
queue<pair<int,int>> q;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
memset(d,0x3f, sizeof d);
int n, m;
cin >> n >> m;
for (int i = 0 ; i < n ; i ++ ) {
string s;
cin >> s;
for (int j = 0 ; s[j] ; j ++ ) {
if (s[j] == '1') {
q.push({i, j});
d[i][j] = 0;
}
}
}
while (q.size()) {
int l = q.size();
for (int i = 0 ; i < l ; i ++ ) {
auto t = q.front();
q.pop();
for (int j = 0 ; j < 4 ; j ++ ) {
int x = t.first + dx[j];
int y = t.second + dy[j];
if (x >= 0 && x < n && y >= 0 && y < m && d[x][y] == 0x3f3f3f3f) {
q.push({x, y});
d[x][y] = min(d[x][y], d[t.first][t.second] + 1);
}
}
}
}
for (int i = 0 ; i < n ; i ++ ) {
for (int j = 0 ; j < m ; j ++ ) cout << d[i][j] << ' ';
cout << endl;
}
return 0;
}