-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0542_updateMatrix.cc
130 lines (127 loc) · 3.25 KB
/
Problem_0542_updateMatrix.cc
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdint.h>
#include <queue>
#include <vector>
using namespace std;
class Solution
{
public:
// bfs
// 从 0 节点开始进行广度遍历
vector<vector<int>> updateMatrix(vector<vector<int>>& mat)
{
int n = mat.size();
int m = mat[0].size();
vector<vector<int>> distance(n, vector<int>(m));
vector<vector<bool>> seen(n, vector<bool>(m));
queue<std::pair<int, int>> q;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (mat[i][j] == 0)
{
q.push({i, j});
seen[i][j] = true;
}
}
}
static constexpr int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!q.empty())
{
auto [x, y] = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nextx = x + directions[i][0];
int nexty = y + directions[i][1];
if (nextx >= 0 && nextx < n && nexty >= 0 && nexty < m && !seen[nextx][nexty])
{
distance[nextx][nexty] = distance[x][y] + 1;
q.push({nextx, nexty});
seen[nextx][nexty] = true;
}
}
}
return distance;
}
// 动态规划
vector<vector<int>> dp(vector<vector<int>>& matrix)
{
int m = matrix.size();
int n = matrix[0].size();
// 初始化动态规划的数组,所有的距离值都设置为一个很大的数
vector<vector<int>> dist(m, vector<int>(n, INT32_MAX / 2));
// 如果 (i, j) 的元素为 0,那么距离为 0
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == 0)
{
dist[i][j] = 0;
}
}
}
// 只有 水平向左移动 和 竖直向上移动,注意动态规划的计算顺序
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i - 1 >= 0)
{
dist[i][j] = std::min(dist[i][j], dist[i - 1][j] + 1);
}
if (j - 1 >= 0)
{
dist[i][j] = std::min(dist[i][j], dist[i][j - 1] + 1);
}
}
}
// 只有 水平向左移动 和 竖直向下移动,注意动态规划的计算顺序
for (int i = m - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
if (i + 1 < m)
{
dist[i][j] = std::min(dist[i][j], dist[i + 1][j] + 1);
}
if (j - 1 >= 0)
{
dist[i][j] = std::min(dist[i][j], dist[i][j - 1] + 1);
}
}
}
// 只有 水平向右移动 和 竖直向上移动,注意动态规划的计算顺序
for (int i = 0; i < m; i++)
{
for (int j = n - 1; j >= 0; j--)
{
if (i - 1 >= 0)
{
dist[i][j] = std::min(dist[i][j], dist[i - 1][j] + 1);
}
if (j + 1 < n)
{
dist[i][j] = std::min(dist[i][j], dist[i][j + 1] + 1);
}
}
}
// 只有 水平向右移动 和 竖直向下移动,注意动态规划的计算顺序
for (int i = m - 1; i >= 0; i--)
{
for (int j = n - 1; j >= 0; j--)
{
if (i + 1 < m)
{
dist[i][j] = std::min(dist[i][j], dist[i + 1][j] + 1);
}
if (j + 1 < n)
{
dist[i][j] = std::min(dist[i][j], dist[i][j + 1] + 1);
}
}
}
return dist;
}
};