forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-matrix.cpp
37 lines (34 loc) · 1.18 KB
/
01-matrix.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
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
queue<pair<int, int>> queue;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
queue.emplace(i, j);
}
else {
matrix[i][j] = numeric_limits<int>::max();
}
}
}
const vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.empty()) {
auto cell = queue.front();
queue.pop();
for (const auto& dir : dirs) {
auto i = cell.first + dir.first;
auto j = cell.second + dir.second;
if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() ||
matrix[i][j] <= matrix[cell.first][cell.second] + 1) {
continue;
}
queue.emplace(i, j);
matrix[i][j] = matrix[cell.first][cell.second] + 1;
}
}
return matrix;
}
};