As Far from Land as Possible
Medium
Topics
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
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
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
- Seed the queue with every land cell. If there is no land or no water, return -1.
- Expand level by level, marking newly reached water cells as visited by turning them into land.
- 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 4Complexity
- 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 distimport java.util.*;
class Solution {
public int maxDistance(int[][] grid) {
int R = grid.length, C = grid[0].length;
ArrayDeque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) q.add(new int[]{r, c});
if (q.isEmpty() || q.size() == R * C) return -1;
int dist = 0;
int[][] dirs = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
while (!q.isEmpty()) {
ArrayDeque<int[]> nq = new ArrayDeque<>();
for (int[] cur : q) {
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 0) {
grid[nr][nc] = 1;
nq.add(new int[]{nr, nc});
}
}
}
if (!nq.isEmpty()) dist++;
q = nq;
}
return dist;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxDistance(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
vector<pair<int,int>> q;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) q.push_back({r, c});
if (q.empty() || (int)q.size() == R * C) return -1;
int dist = 0;
int dirs[4][2] = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
}
};
while (!q.empty()) {
vector<pair<int,int>> nq;
for (auto& cur : q) {
for (int d = 0; d < 4; d++) {
int nr = cur.first + dirs[d][0], nc = cur.second + dirs[d][1];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 0) {
grid[nr][nc] = 1;
nq.push_back({nr, nc});
}
}
}
if (!nq.empty()) dist++;
q = nq;
}
return dist;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maxDistance = function(grid) {
const R = grid.length, C = grid[0].length;
let q = [];
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (grid[r][c] === 1) q.push([r, c]);
if (q.length === 0 || q.length === R * C) return -1;
let dist = 0;
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
while (q.length) {
const nq = [];
for (const [r, c] of q) {
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] === 0) {
grid[nr][nc] = 1;
nq.push([nr, nc]);
}
}
}
if (nq.length) dist++;
q = nq;
}
return dist;
};