标签:++i 矩阵 turn const 例题 main std front contain
多源bfs就是一开始有很多的源头,不只一个源点。处理的方法:一开始直接把所有源点放入队列;或者建立一个虚拟源点,虚拟源点到每个源点的距离为0
acwing173矩阵距离
给定一个N行M列的01矩阵A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为:
dist(A[i][j],A[k][l])=|i?k|+|j?l|
输出一个N行M列的整数矩阵B,其中:
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1)dist(A[i][j],A[x][y])
N、M~1e3
#include <bits/stdc++.h>
using namespace std;
struct POS {
int x, y, step;
};
int const N = 1e3 + 10;
int a[N][N], b[N][N];
int n, m;
queue<POS> q;
int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
void bfs() {
while (q.size()) {
auto t = q.front();
q.pop();
int x = t.x, y = t.y, step = t.step;
for (int i = 0; i < 4; ++i) {
int next_x = x + dx[i], next_y = y + dy[i];
if (next_x < 1 || next_x > n || next_y < 1 || next_y > m) continue;
if (b[next_x][next_y] != -1) continue;
if (!a[next_x][next_y]) b[next_x][next_y] = step + 1;
q.push({next_x, next_y, step + 1});
}
}
}
int main() {
memset(b, -1, sizeof b);
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
string s;
cin >> s;
for (int j = 0; j < s.size(); ++j) {
a[i][j + 1] = s[j] - ‘0‘;
if (a[i][j + 1]) {
b[i][j + 1] = 0;
q.push({i, j + 1, 0}); // 把所有源点放入队列
}
}
}
bfs();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)
cout << b[i][j] << " ";
cout << endl;
}
return 0;
}
标签:++i 矩阵 turn const 例题 main std front contain
原文地址:https://www.cnblogs.com/spciay/p/13383109.html