-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01Matrix_542.cpp
51 lines (41 loc) · 1.48 KB
/
01Matrix_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
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 542. 01 Matrix
~ Link : https://leetcode.com/problems/01-matrix/
*/
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int r = mat.size(), c = mat[0].size();
vector<vector<int> > res(r, vector<int> (c, 0));
vector<vector<bool> > visited(r, vector<bool> (c, false));
queue<vector<int> > todo;
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
if (mat[i][j] == 0) {
todo.push({i, j, 0});
visited[i][j] = true;
}
}
}
static int row4D[] = {-1, 0, 1, 0};
static int col4D[] = {0, 1, 0, -1};
while (!todo.empty()) {
vector<int> curr = todo.front();
todo.pop();
for (int k = 0; k < 4; ++k) {
int adj_r = curr[0] + row4D[k];
int adj_c = curr[1] + col4D[k];
if ((adj_r >= 0 && adj_r < r) && (adj_c >= 0 && adj_c < c) &&
!visited[adj_r][adj_c] && mat[adj_r][adj_c] == 1) {
res[adj_r][adj_c] = curr[2] + 1;
todo.push({adj_r, adj_c, res[adj_r][adj_c]});
visited[adj_r][adj_c] = true;
}
}
}
return res;
}
};
// Time Complexity - O(r * c)
// Auxiliary Space - O(r * c)