矩阵距离
作者:
木可柯
,
2024-05-04 15:18:04
,
所有人可见
,
阅读 8
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int g[N][N], dist[N][N], dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int n, m;
void bfs()
{
memset(dist, -1, sizeof dist);
queue<PII> q;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
//找到多个源点然后卡死蔓延查找
if(g[i][j] == 1) {
dist[i][j] = 0;
q.push({i, j});
}
}
while(q.size()) {
PII t = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int a = t.x + dir[i][0], b = t.y + dir[i][1];
//出界了
if(a < 0 || a >= n || b < 0 || b >= m) continue;
//之前记录的一定是最短路径
if(dist[a][b] != -1) continue;
dist[a][b] = dist[t.x][t.y] + 1;
q.push({a, b});
}
}
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
char c;
cin >> c;
g[i][j] = c - '0';
}
bfs();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
cout << dist[i][j] << " ";
cout << endl;
}
return 0;
}