#1162
As Far from Land as Possible
specialist · 830 · lc medium +31 · verified · 52.2% accepted · 4,266 likes · top 42%
Description
You are given an n x n grid where each cell is either 0 (water) or 1 (land). Identify the water cell whose Manhattan distance to the nearest land cell is the greatest, and return that distance. Return -1 if there are no land cells or no water cells.
The Manhattan distance between cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Code
1
2
3