AcWing 173. 矩阵距离
宋标 Lv5

题目

给定一个 列的 矩阵 之间的曼哈顿距离定义为:

输出一个 列的整数矩阵 ,其中:

输入格式

第一行两个整数

接下来一个 列的 矩阵,数字之间没有空格。

输出格式

一个 列的矩阵 ,相邻两个整数之间用一个空格隔开。

数据范围

输入样例:

3 4
0001
0011
0110

输出样例:

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

题解

主要思路是前一个节点的路径+1,bfs最先到达的节点表示最短距离。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

typedef pair<int,int> PII;

const int N = 1010, INF = 0x3f3f3f3f;

int A[N][N], B[N][N];
int n, m;
queue<PII> q;

int main()
{
memset(B, 0x3f, sizeof B);
cin >> n >> m;
for (int i = 0; i < n; ++ i)
{
string s;
cin >> s;
for (int j = 0; j < s.size(); ++ j)
{
A[i][j] = s[j] - '0';
if (A[i][j] == 1) q.push({i, j}), B[i][j] = 0;
}
}

int xy[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

while (!q.empty())
{
auto t = q.front();
q.pop();
int dx = t.first, dy = t.second;

for (int i = 0; i < 4; ++ i)
{
int x = dx + xy[i][0], y = dy + xy[i][1];
if (x >= 0 && x < n && y >= 0 && y < m && B[x][y] == INF)
{
B[x][y] = B[dx][dy] + 1;
q.push({x, y});
}
}
}


for (int i = 0; i < n; ++ i)
{
for (int j = 0; j < m; ++ j)
printf("%d ", B[i][j]);
puts("");
}

return 0;
}
 评论