-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathas_far_from_land_as_possible.cpp
34 lines (33 loc) · 1.03 KB
/
as_far_from_land_as_possible.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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
queue<pair<int,int>> q;
int steps = 0,r = grid.size(),c = grid[0].size();
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
if(grid[i][j] == 1) {
q.push({i-1, j});
q.push({i+1, j});
q.push({i, j-1});
q.push({i, j+1});
}
}
}
while(!q.empty()) {
int size = q.size();
steps++;
for(int k = 0; k < size; k++) {
int i = q.front().first, j = q.front().second;
q.pop();
if(i >= 0 && j >= 0 && i < r && j < c&& grid[i][j] == 0) {
grid[i][j] = steps;
q.push({i-1, j});
q.push({i+1, j});
q.push({i, j-1});
q.push({i, j+1});
}
}
}
return steps == 1 ? -1 : steps - 1;
}
};