[LeetCode] As Far from Land as Possible

1162. As Far from Land as Possible

Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.

The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int dy[4] = {-1,0,1,0}, dx[4] = {0,1,0,-1};
queue<pair<int,int>> q;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(grid[i][j])
q.push({i,j});
int dis = -1;
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !grid[ny][nx]) {
grid[ny][nx] = 1;
q.push({ny,nx});
}
}
}
dis++;
}

return dis == 0 ? -1 : dis;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/24/PS/LeetCode/as-far-from-land-as-possible/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.