As Far from Land as Possible Problem
Description
LeetCode Problem 1162.
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|.
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.
Constraints:
n == grid.lengthn == grid[i].length1 <= n <= 100grid[i][j]is0or1
Solution
Approach: Multi-Source BFS from All Land
Running a BFS from every water cell to find its nearest land would cost O(n4). Instead, turn it around and start from all land cells at once.
Put every land cell in the queue, then expand one layer at a time. In the first layer we reach every water cell at distance 1 from the nearest land, in the second layer those at distance 2, and so on, because BFS reaches each cell first by the shortest path from whichever land cell is closest. In a grid with no obstacles, that BFS distance is exactly the Manhattan distance to the nearest land.
When we reach a water cell we set it to 1 so it is never visited again. The number of layers that still found new water is the distance of the farthest water cell, which is the answer.
If the grid has no land or no water at all, there is no answer, so check that before the search and return -1.
Complexity: O(n2) time and space: each cell enters the queue at most once.
from collections import deque
class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
# Start from every land cell at once (multi-source BFS).
q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j] == 1)
if len(q) == 0 or len(q) == n * n:
return -1 # no land, or no water
ans = -1
while q:
for _ in range(len(q)): # one layer = one more step away from land
i, j = q.popleft()
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
grid[x][y] = 1 # reached for the first time: mark it visited
q.append((x, y))
ans += 1
return ans