As Far from Land as Possible (LeetCode 1162): Solution and Explanation

Medium
Array
Dynamic Programming
Breadth First Search
Matrix

In a square grid of land and water, find the water cell whose nearest land is farthest away and return that distance.

Intuition

The obvious idea runs a BFS from each water cell to find its nearest land. That repeats almost the same search for every cell and costs O(n^4) on a 100x100 grid.

Turn it around. Picture every land cell as a coastline and let water rise from all of them at the same speed. After one step the flood covers every cell at distance 1 from some land, after two steps every cell at distance 2, and so on.

That is a breadth-first search seeded with all land cells at once. A water cell is first reached by the wave from its closest land, so the level at which it floods is exactly its distance to the nearest land.

The last level that still floods new water holds the cells farthest from land, and its number is the answer. If there is no land, nothing floods; if there is no water, there is nothing to measure. Both return -1.

Approach: Multi-source BFS

  1. Push every land cell onto a queue.
  2. If the queue is empty or holds all n * n cells, return -1.
  3. Set dist = -1. While the queue is not empty, increase dist and process exactly the cells currently in it.
  4. For each popped cell, look at its four neighbours. Every in-bounds water neighbour is marked as land and pushed.
  5. When the queue empties, return dist: the level number of the last cells reached.

Step-by-step example

grid = [[1,0,1],[0,0,0],[1,0,1]]
  1. The four corners are land. All of them go into the queue together.
  2. Level 0 (dist = 0): the corners flood their neighbours (0,1), (1,0), (1,2) and (2,1), each at distance 1.
  3. Level 1 (dist = 1): those four cells flood the center (1,1) at distance 2.
  4. Level 2 (dist = 2): the center has no dry neighbour. The queue empties and the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def maxDistance(self, grid: List[List[int]]) -> int:
3        n = len(grid)
4        queue = deque((r, c) for r in range(n) for c in range(n) if grid[r][c] == 1)
5        if len(queue) == 0 or len(queue) == n * n:
6            return -1
7        dist = -1
8        while queue:
9            dist += 1
10            for _ in range(len(queue)):
11                r, c = queue.popleft()
12                for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
13                    if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
14                        grid[nr][nc] = 1
15                        queue.append((nr, nc))
16        return dist
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Each cell is pushed and popped at most once, and each pop checks four neighbours.

Space

O(n^2)

The queue can hold a large part of the grid. Marking flooded cells in the grid itself avoids a separate visited array.

Other approaches

Two-pass dynamic programming (time O(n^2), space O(1) beyond the grid)

Sweep top-left to bottom-right taking the minimum from the top and left neighbours plus one, then sweep back from the bottom-right using the bottom and right neighbours. This computes the same Manhattan distances without a queue.

BFS from each water cell (time O(n^4), space O(n^2))

For each water cell, search until the first land cell. Correct but repeats nearly identical work for every cell.

Common mistakes

  • Forgetting the all-land and all-water cases. Without the early check, an all-land grid returns 0 instead of -1.
  • Starting dist at 0 and incrementing at the top of every level, which overcounts by one. Starting at -1 makes the land level count as 0.
  • Marking cells visited when they are popped instead of when they are pushed, which lets the same cell enter the queue several times.
  • Using Euclidean distance. The problem asks for Manhattan distance, which is exactly what four-direction BFS measures.

Frequently asked questions

Why does starting from all land at once give the nearest land for every cell?

All sources start at level 0 and the waves advance one step per level. Whichever land is closest to a water cell reaches it first, and since a cell is never revisited, the level it records is its distance to that nearest land.

Why is BFS distance equal to Manhattan distance here?

The grid has no obstacles: water cells can be crossed freely. The shortest four-direction path between two cells therefore has exactly |dx| + |dy| steps.

Is this the same as 01 Matrix or Rotting Oranges?

Yes, it is the same multi-source BFS. 01 Matrix returns every distance, Rotting Oranges returns the time the last orange rots, and this problem returns the largest distance.

What is the time complexity?

O(n^2) time and O(n^2) space for an n x n grid, since each cell enters the queue at most once.