My first instinct was BFS from each water cell individually, which would've been way too slow.
Use a multi-source BFS starting from all land cells simultaneously to compute the shortest distance to the nearest land for every water cell. Then, scan the distance grid to find the maximum distance among water cells. This approach runs in O(n²) time and handles edge cases (no land or no water) by returning -1.
Pro tip: Clarify that the multi-source BFS is essentially a dynamic programming approach that propagates distances level by level, and mention that you can optimize space by using a 2D array of distances or by modifying the grid in-place if allowed.
First, verify if the grid contains both land and water. If either is missing, return -1 immediately.
Add all land cells to a queue and set their distance to 0. For water cells, initialize distance to infinity (or a large number).
Perform BFS from all land cells simultaneously, updating the distance of each water cell to the minimum distance from any land cell.
After BFS, scan the distance grid to find the maximum distance among all water cells. Return that maximum.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.