AcWing 173. 矩阵距离
原题链接
简单
作者:
我要出去乱说
,
2021-02-03 11:01:45
,
所有人可见
,
阅读 162
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n, m;
char g[N][N];
int d[N][N];
void bfs()
{
memset(d, -1, sizeof d);
queue<PII> q;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
if (g[i][j] == '1')
{
q.push({i, j}); //遍历g,将初始状态存入队列,队列中存的是可拓展点
d[i][j] = 0; //队列中存的是点i到j这条路径,d中存的是路径长度
}
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (q.size()) //当还存在可拓展点时,继续拓展
{
auto t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; i ++ ) //每次往上下左右四个方向拓展一格
{
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && d[a][b] == -1)
{
d[a][b] = d[x][y] + 1;
q.push({a, b}); //存入拓展点状态
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i ++ ) scanf("%s", g[i]);
bfs();
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < m; j ++ )
printf("%d ", d[i][j]);
puts("");
}
return 0;
}