forked from jhflorey/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-matrix.cpp
executable file
·41 lines (40 loc) · 1.25 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
/*
*
* Tag: BFS
* Time: O(nm)
* Space: O(nm)
*/
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
if(matrix.size() == 0)
return matrix;
int n = matrix.size(), m = matrix[0].size();
vector<vector<int>> ans(n, vector<int>(m, n*m));
queue<pair<int,int>> q;
pair<int,int> cur, nxt;
for(int i = 0; i < n; ++ i){
for(int j = 0; j < m; ++ j){
if(matrix[i][j] == 0){
ans[i][j] = 0;
q.push(make_pair(i,j));
}
}
}
while(!q.empty()){
cur = q.front();
q.pop();
for(int i = 0; i < 4; ++ i){
nxt.first = cur.first + dir[i][0], nxt.second = cur.second + dir[i][1];
if((nxt.first >= 0 && nxt.first < n && nxt.second >= 0 && nxt.second < m) &&
ans[nxt.first][nxt.second] > ans[cur.first][cur.second] + 1){
ans[nxt.first][nxt.second] = ans[cur.first][cur.second] + 1;
q.push(make_pair(nxt.first, nxt.second));
}
}
}
return ans;
}
private:
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
};