Skip to content

Commit 19f00bc

Browse files
Create as_far_from_land_as_possible.cpp
1 parent 5b76531 commit 19f00bc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

as_far_from_land_as_possible.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
int maxDistance(vector<vector<int>>& grid) {
4+
queue<pair<int,int>> q;
5+
int steps = 0,r = grid.size(),c = grid[0].size();
6+
7+
for(int i = 0; i < r; i++) {
8+
for(int j = 0; j < c; j++) {
9+
if(grid[i][j] == 1) {
10+
q.push({i-1, j});
11+
q.push({i+1, j});
12+
q.push({i, j-1});
13+
q.push({i, j+1});
14+
}
15+
}
16+
}
17+
while(!q.empty()) {
18+
int size = q.size();
19+
steps++;
20+
for(int k = 0; k < size; k++) {
21+
int i = q.front().first, j = q.front().second;
22+
q.pop();
23+
if(i >= 0 && j >= 0 && i < r && j < c&& grid[i][j] == 0) {
24+
grid[i][j] = steps;
25+
q.push({i-1, j});
26+
q.push({i+1, j});
27+
q.push({i, j-1});
28+
q.push({i, j+1});
29+
}
30+
}
31+
}
32+
return steps == 1 ? -1 : steps - 1;
33+
}
34+
};

0 commit comments

Comments
 (0)