-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path01 Matrix.cpp
53 lines (41 loc) · 1.33 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Solution by Rahul Surana
***********************************************************
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
***********************************************************
*/
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(),n = mat[0].size();
queue<vector<int>> q;
vector<vector<bool>> v(m,vector<bool>(n,false));
int step = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(mat[i][j] == 0){
q.push({i,j});
}
}
}
while(!q.empty()){
int s = q.size();
while(s--){
auto a = q.front();
auto x = a[0], y = a[1];
q.pop();
if(x < 0 || x > m-1 || y < 0 || y > n-1 || v[x][y]) continue;
if(mat[x][y] != 0)
mat[x][y] = step;
v[x][y] = true;
q.push({x+1,y});
q.push({x,y+1});
q.push({x-1,y});
q.push({x,y-1});
}
step++;
}
return mat;
}
};