forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
as-far-from-land-as-possible.cpp
41 lines (40 loc) · 1.27 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
35
36
37
38
39
40
41
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
queue<pair<int, int>> q;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[i].size(); ++j) {
if (grid[i][j]) {
q.emplace(i, j);
}
}
}
if (q.size() == grid.size() * grid[0].size()) {
return -1;
}
int level = -1;
while (!q.empty()) {
queue<pair<int, int>> next_q;
while (!q.empty()) {
const auto [x, y] = q.front(); q.pop();
for (const auto& [dx, dy] : directions) {
const auto& nx = x + dx;
const auto& ny = y + dy;
if (!(0 <= nx && nx < grid.size() &&
0 <= ny && ny < grid[0].size() &&
grid[nx][ny] == 0)) {
continue;
}
next_q.emplace(nx, ny);
grid[nx][ny] = 1;
}
}
q = move(next_q);
++level;
}
return level;
}
};