Problem Description
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 Manhattan distance to the nearest land cell is maximized. Return the maximum distance. If the grid contains only water or only land, return -1.
Key Insights
- Use a multi-source Breadth-First Search (BFS) starting from all the land cells simultaneously.
- BFS expansion naturally calculates the minimum Manhattan distance from each water cell to the nearest land.
- Processing cells level-by-level ensures that each water cell is labeled with its shortest distance from any land cell.
- If either no land or no water exists, return -1 immediately.
Space and Time Complexity
Time Complexity: O(n^2) – Every cell in the grid is visited at most once. Space Complexity: O(n^2) – In the worst-case, the BFS queue may contain a large fraction of the cells.
Solution
To solve the problem, we perform a multi-source BFS starting from every land cell. We initially enqueue all land cell coordinates. Then, using BFS, we expand outwards to visit neighboring water cells. For each water cell encountered, mark the cell with the distance (incremented from the nearest land cell) and add it to the queue. The final maximum distance is determined by the last level of water cell that gets processed. This converts the grid into a distance map, where the value in a water cell minus one gives the Manhattan distance from the nearest land cell.