As Far from Land as Possible - Problem
As Far from Land as Possible
Imagine you're a marine biologist studying ocean currents and need to find the most remote water location from any land mass. Given an
The distance is measured using Manhattan distance: the distance between two cells
Goal: Return the maximum distance from any water cell to the nearest land cell. If the grid contains only land or only water, return
Example: In a 3×3 grid with land at corners, the center water cell would be farthest from all land masses.
Imagine you're a marine biologist studying ocean currents and need to find the most remote water location from any land mass. Given an
n × n grid representing a map where 0 represents water and 1 represents land, your task is to find a water cell that is as far as possible from any land cell.The distance is measured using Manhattan distance: the distance between two cells
(x₀, y₀) and (x₁, y₁) is |x₀ - x₁| + |y₀ - y₁|.Goal: Return the maximum distance from any water cell to the nearest land cell. If the grid contains only land or only water, return
-1.Example: In a 3×3 grid with land at corners, the center water cell would be farthest from all land masses.
Input & Output
example_1.py — Basic Grid
$
Input:
grid = [[1,0,1],[0,0,0],[1,0,1]]
›
Output:
2
💡 Note:
The center water cell (1,1) is farthest from any land, with Manhattan distance 2 to all corner land cells.
example_2.py — Single Land
$
Input:
grid = [[1,0,0],[0,0,0],[0,0,0]]
›
Output:
4
💡 Note:
The bottom-right water cell (2,2) is farthest from the single land cell at (0,0), with distance |2-0| + |2-0| = 4.
example_3.py — Edge Case
$
Input:
grid = [[1,1],[1,1]]
›
Output:
-1
💡 Note:
Grid contains only land cells, so there's no water to measure distance from.
Visualization
Tap to expand
Understanding the Visualization
1
Deploy Boats
Launch rescue boats from all islands simultaneously (multi-source BFS)
2
Expand Search
Boats spread outward in waves, marking distances as they go
3
Find Remote Location
The last water location reached is farthest from all land
4
Mission Complete
Return the maximum distance found for optimal supply drop
Key Takeaway
🎯 Key Insight: Multi-source BFS naturally finds the optimal location by expanding from all starting points simultaneously, ensuring we discover the maximum distance efficiently.
Time & Space Complexity
Time Complexity
O(n²)
Each cell is visited exactly once during BFS traversal
⚠ Quadratic Growth
Space Complexity
O(n²)
Distance matrix and BFS queue both use O(n²) space
⚠ Quadratic Space
Constraints
- n == grid.length
- n == grid[i].length
- 1 ≤ n ≤ 100
- grid[i][j] is 0 or 1
- Distance is calculated using Manhattan distance formula
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code