![image](https://img2022.cnblogs.com/blog/2674359/202208/2674359-20220803215736646-543152179.png)
多源 BFS
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1000 + 10;
#define x first
#define y second
int n, m;
char g[N][N];
int d[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void bfs()
{
memset(d, -1, sizeof d);
queue<pair<int,int>> q;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
if (g[i][j] == '1') {
q.push({i, j});
d[i][j] = 0;
}
while (q.size()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i ++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 1 || a > n || b < 1 || b > m || d[a][b] != -1)
continue;
d[a][b] = d[t.x][t.y] + 1;
q.push({a, b});
}
}
}
void solve()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
cin >> g[i][j];
bfs();
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++)
cout << d[i][j] << ' ';
cout << endl;
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
- 可以假象一个单源点,源点到所有为 "1" 的点的距离为 \(0\),之后就转化为单源最短路模型,用 \(BFS\) 求解