AcWing 3083. 矩阵距离
原题链接
简单
作者:
糖醋拐杖_8
,
2024-02-24 13:28:00
,
所有人可见
,
阅读 171
#include <iostream>
#include <cstring>
#include <algorithm>
#define x first
#define y second
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
char g[N][N];
bool st[N][N];
int d[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n,m;
queue <PII> q;
int bfs()
{
while (q.size())
{
PII 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 < 0 || b < 0 || a >= n || b >= m) continue;
if (st[a][b]) continue;
st[a][b] = true;
d[a][b] = d[t.x][t.y] + 1;
q.push({a,b});
}
}
return 0;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ ) cin >> g[i];
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < m; j ++ )
{
if (g[i][j] == '1')
{
q.push({i,j});
st[i][j] = true;
}
}
}
bfs();
for (int i = 0; i < n; i ++ )
{
for (int j = 0;j < m;j++)
{
cout << d[i][j] << " ";
}
puts("");
}
return 0;
}