-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-Matrix.cpp
More file actions
43 lines (39 loc) · 1.21 KB
/
Copy path01-Matrix.cpp
File metadata and controls
43 lines (39 loc) · 1.21 KB
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
// Company tags: Flipkart, Snowflake, DoorDash
class Solution {
public:
// T.C: O(n * m);
// S.C: O(n * m);
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
vector<vector<int>> res(n, vector<int>(m, -1));
queue<pair<int, int>> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0) {
res[i][j] = 0;
q.push({i, j});
}
}
}
while(!q.empty()){
int k = q.size();
while(k--){
auto temp = q.front();
q.pop();
int i = temp.first;
int j = temp.second;
for(auto& dir : dirs){
int i_ = i + dir[0];
int j_ = j + dir[1];
if(i_ >= 0 && i_ < n && j_ >= 0 && j_< m && res[i_][j_] == -1){
res[i_][j_] = 1 + res[i][j];
q.push({i_, j_});
}
}
}
}
return res;
}
};