题目描述
假设我们有一个矩阵,其元素值非 0 即 1:

a11 … … a1m

… … … … …

an1 … … anm

定义 aij 与 akl 之间的距离为 D(aij,akl)=abs(i−k)+abs(j−l)。

现求每个元素到最近的元素值为 1 的元素的距离。

输入
​ 输入文件的第一行为两个整数,分别代表 n 和 m。

接下来的 n 行,第 i 行的第 j 个字符代表 aij。

输出
​ 输出包含 N 行,每行 M 个用空格分开的数字,其中第 i 行第 j 个数字代表 Min(D(aij,axy)1≤x≤N,1≤y≤m,且 axy=1。

样例输入

3 4
0001
0011
0110

样例输出

3 2 1 0
2 1 0 0
1 0 0 1

数据规模与约定
​ 时间限制:10 s

内存限制:256 M

100% 的数据保证 1≤M,N≤1000

#include <iostream>
#include <queue>
using namespace std;

struct node {
int x,y, step;
};
int dir[4][2] = { 1,0,0,1,-1,0,0,-1 };
int n, m;
int ans[1005][1005];
char map[1005][1005];
queue<node> que;

int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> map[i][j];
if (map[i][j] == '1') {
que.push({ i,j,0 });
ans[i][j] = -1;
}
}
}
while (!que.empty()) {
node t = que.front();
que.pop();
for (int i = 0; i < 4; i++) {
int x = t.x + dir[i][0];
int y = t.y + dir[i][1];
if (x<1 || y<1 || x>n || y>m || ans[x][y]) {
continue;
}
ans[x][y] = t.step + 1;
que.push({ x,y,ans[x][y] });
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j != 1) cout << " ";
if (ans[i][j] == -1) {
cout << 0;
}
else {
cout << ans[i][j];
}
}
cout << endl;
}
return 0;
}