AcWing 173. 矩阵距离
原题链接
简单
作者:
hai阿卢
,
2021-03-08 21:48:36
,
所有人可见
,
阅读 252
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1010;
typedef pair<int, int> PII;
char a[N][N];
bool s[N][N];
int d[N][N];
queue<PII> q;
void Bfs(int n, int m)
{
memset(d, 0x3f, sizeof(d));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(a[i][j] == '1')
{
q.push({i, j});
d[i][j] = 0;
s[i][j] = true;
}
}
}
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
while(!q.empty())
{
PII it = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int x = it.first + dx[i];
int y = it.second + dy[i];
if(x >= 0 && x <= n && y >= 0 && y <= m && !s[x][y])
{
q.push({x, y});
d[x][y] = d[it.first][it.second] + 1;
s[x][y] = true;
}
}
}
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < n; i++) scanf("%s", a[i]);
Bfs(n, m);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cout << d[i][j] << " ";
}
cout << endl;
}
return 0;
}