-
Notifications
You must be signed in to change notification settings - Fork 3
/
542.cpp
38 lines (37 loc) · 1.22 KB
/
542.cpp
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
class Solution {
public:
vector<pair<int, int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<vector<int>> res(m, vector<int>(n, 0));
queue<pair<int, int>> q;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 0) {
q.push({i, j});
mat[i][j] = -1;
}
}
}
int length = 1;
while (!q.empty()) {
int k = q.size();
while (k--) {
auto [x, y] = q.front();
q.pop();
for (auto direction : directions) {
int nextX = x + direction.first;
int nextY = y + direction.second;
if (nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) continue;
if (mat[nextX][nextY] == -1) continue;
mat[nextX][nextY] = -1;
res[nextX][nextY] = length;
q.push({nextX, nextY});
}
}
length++;
}
return res;
}
};