As Far from Land as Possible

Medium

Topics
GraphBFSMatrix

Given a grid where 1 is land and 0 is water, find the water cell whose Manhattan distance to the nearest land cell is maximized, and return that distance. If the grid has no water or no land, return -1.

Example 1

0L1L11212L1L012
landthe answer cell
Every water cell is labelled with its Manhattan distance to the nearest land.
2D grid — one row per line.
Input:  grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2

Example 2

0L1211232234012
landthe answer cell
Input:  grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4

Constraints

  • 1 <= n <= 100
  • grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

For each water cell we want its distance to the nearest land, then the largest of those. Running a BFS from every water cell is O((m*n)^2) and far too slow.

Invert it. Rather than asking each water cell to find land, start from all land cells at once and let the wave spread outward. A BFS seeded with every land cell computes, in one sweep, the distance from each water cell to its nearest land — because the first wave to reach a cell necessarily came from the closest source.

💡 Multi-source BFS: put every source in the initial queue at distance 0. It is the standard trick for "nearest of many targets", and it costs exactly one ordinary BFS rather than one per source.

The answer is the distance at which the last cell is reached, so processing level by level and counting levels gives it directly.

Approach

  1. Seed the queue with every land cell. If there is no land or no water, return -1.
  2. Expand level by level, marking newly reached water cells as visited by turning them into land.
  3. Return the number of levels expanded.

Dry Run

grid   1 0 1
       0 0 0
       1 0 1

level 0: the four corners are land
level 1: reaches (0,1) (1,0) (1,2) (2,1)   -- all edge midpoints
level 2: reaches (1,1), the centre

the centre is the last cell reached, at distance 2

answer 2

grid   1 0 0
       0 0 0
       0 0 0
level 1: (0,1) (1,0)
level 2: (0,2) (1,1) (2,0)
level 3: (1,2) (2,1)
level 4: (2,2)        -> answer 4

Complexity

  • Time — O(m*n): each cell enters the queue at most once and is examined with four neighbour checks. The claim of O(n^2) is the same thing for a square grid.
  • Space — O(m*n): the queue, which in the worst case holds a whole level, and that level can be a constant fraction of the grid.

Common Pitfalls

  • Running a separate BFS per water cell. Correct and quadratically too slow; the inversion is the entire point.
  • Returning -1 only for an all-water grid. It must also be returned when there is no water at all, since no distance exists.
  • Marking cells visited when dequeued rather than when enqueued, which lets the same cell enter the queue from several neighbours and breaks the level counting.
  • Counting the land level as distance 1. Land is distance 0, so the answer is the number of expansion rounds.
  • Using Manhattan distance to the nearest land directly. The grid has no obstacles here so it happens to agree, but the BFS is what generalises.

Full Solution — all languages

class Solution:
    def maxDistance(self, grid):
        R, C = len(grid), len(grid[0])
        q = [(r, c) for r in range(R) for c in range(C) if grid[r][c] == 1]
        if len(q) == 0 or len(q) == R * C:
            return -1
        dist = 0
        dirs = [(1,0),(-1,0),(0,1),(0,-1)]
        while q:
            nq = []
            for r, c in q:
                for dr, dc in dirs:
                    nr, nc = r+dr, c+dc
                    if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 0:
                        grid[nr][nc] = 1
                        nq.append((nr, nc))
            if nq:
                dist += 1
            q = nq
        return dist
SensAI
Beta
Tap the mic to stop voice mode