Skip to problem
←

As Far from Land as Possible

Medium 0 attempts

Given an n × n grid of water (0) and land (1), find each water cell’s distance to its nearest land cell. Return the largest of those distances.

Distance is Manhattan distance: |r1 - r2| + |c1 - c2|, using horizontal and vertical steps. If there is no water or no land, return -1.

Function contract

Implement maxDistance(grid), where grid is an n × n array with 0 for water and 1 for land.

Output: The largest distance from any water cell to its nearest land cell, or -1 if there is no water or no land.

Example 1

Input
grid = [[1,0,1],[0,0,0],[1,0,1]]
Output
2

Example 2

Input
grid = [[1,0,0],[0,0,0],[0,0,0]]
Output
4
Visual Aid
Distance to the nearest land
L1L121L1L

L marks land. Numbers show nearest-land distance for water cells. The center gives the maximum, 2.

Constraints
  • n == grid.length == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1
Topics

Multi-source BFS

Start BFS from all land cells simultaneously and expand outward.

javascript
function maxDistance(grid) {
  const n = grid.length, q = [];
  for (let i = 0; i < n; i++)
    for (let j = 0; j < n; j++)
      if (grid[i][j] === 1) q.push([i, j]);
  if (q.length === 0 || q.length === n * n) return -1;
  const dirs = [[0,1],[0,-1],[1,0],[-1,0]];
  let dist = -1;
  let head = 0;
  while (head < q.length) {
    dist++;
    const size = q.length - head;
    for (let k = 0; k < size; k++) {
      const [r, c] = q[head++];
      for (const [dr, dc] of dirs) {
        const nr = r+dr, nc = c+dc;
        if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] === 0) {
          grid[nr][nc] = 1; q.push([nr, nc]);
        }
      }
    }
  }
  return dist;
}

Time: O(n²) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript