Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
Example 1:
Input: grid = [[1,0,1],[0,0,0],[1,0,1]] Output: 2 Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]] Output: 4 Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Constraints:
n == grid.lengthn == grid[i].length1 <= n <= 100grid[i][j] is 0 or 1When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine looking at a vast grid where some spots are land and others are water, and you want to find a water spot that is as far away from any land as possible. The brute force approach involves looking at every single water spot one by one, measuring its distance to every single land spot, and finding the maximum of these minimum distances.
Here's how the algorithm would work step-by-step:
def max_distance(grid): grid_rows = len(grid) grid_cols = len(grid[0]) water_spots = [] land_spots = [] # Collect all water and land coordinates to evaluate distances between them later for row_index in range(grid_rows): for col_index in range(grid_cols): if grid[row_index][col_index] == 0: water_spots.append((row_index, col_index)) else: land_spots.append((row_index, col_index)) if not water_spots or not land_spots: return -1 maximum_distance = -1 # Evaluate every water spot to find its minimum distance to any land spot for water_coordinate in water_spots: minimum_land_distance = float('inf') for land_coordinate in land_spots: current_distance = abs(water_coordinate[0] - land_coordinate[0]) + abs(water_coordinate[1] - land_coordinate[1]) if current_distance < minimum_land_distance: minimum_land_distance = current_distance if minimum_land_distance > maximum_distance: maximum_distance = minimum_land_distance # Return the maximum found among all minimum distances to satisfy the problem requirement return maximum_distanceInstead of measuring the distance outward from every single ocean cell, the optimal strategy works in reverse by starting from all the land areas simultaneously. By spreading outward step-by-step like ripples on water, we can find the maximum distance to the furthest ocean in the most direct way possible.
Here's how the algorithm would work step-by-step:
from collections import deque
def max_distance(grid):
grid_dimension = len(grid)
queue_for_bfs = deque()
# Multi-source BFS requires seeding all land cells simultaneously to track minimum distance.
for row_index in range(grid_dimension):
for col_index in range(grid_dimension):
if grid[row_index][col_index] == 1:
queue_for_bfs.append((row_index, col_index))
if not queue_for_bfs or len(queue_for_bfs) == grid_dimension * grid_dimension:
return -1
maximum_distance = -1
row_offsets = [-1, 1, 0, 0]
col_offsets = [0, 0, -1, 1]
# Expanding outward layer by layer ensures we compute the shortest path from land to water.
while queue_for_bfs:
current_row, current_col = queue_for_bfs.popleft()
for direction_index in range(4):
neighbor_row = current_row + row_offsets[direction_index]
neighbor_col = current_col + col_offsets[direction_index]
if 0 <= neighbor_row < grid_dimension and 0 <= neighbor_col < grid_dimension and grid[neighbor_row][neighbor_col] == 0:
grid[neighbor_row][neighbor_col] = grid[current_row][current_col] + 1
maximum_distance = max(maximum_distance, grid[neighbor_row][neighbor_col])
queue_for_bfs.append((neighbor_row, neighbor_col))
# Subtracting one is necessary because land started at 1 instead of 0 distance.
return maximum_distance - 1| Case | How to Handle |
|---|---|
| Grid contains only land cells with no water present | The initial queue scan will find no water, resulting in a distance of -1 as required by the problem statement. |
| Grid contains only water cells with no land present | The initial queue will be empty, allowing the algorithm to return -1 immediately before processing. |
| Minimum possible grid size of 1x1 containing either land or water | Since there is no opposite cell type, the algorithm naturally returns -1 due to the lack of both water and land. |
| A single land cell surrounded entirely by water in a large grid | Multi-source breadth-first search correctly expands outward from the single land cell to compute the maximum Manhattan distance. |
| A single water cell surrounded entirely by land | The breadth-first search will reach this water cell in the first step, yielding a maximum distance of 1. |
| Maximum-sized grid limits with memory and time constraints | Using an in-place visited structure or distance matrix ensures the breadth-first search runs efficiently within optimal time and space limits. |
| Checkerboard or alternating patterns of land and water | Breadth-first search guarantees shortest paths to the nearest land, accurately processing complex alternating topologies layer by layer. |