I started thinking about running BFS from each water cell individually which would have been way too slow.
Use multi-source BFS starting from all land cells simultaneously to compute the shortest distance to the nearest land for every water cell. Then return the maximum distance found, handling edge cases where there is no land or no water by returning -1.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, achieving O(n^2) time, and explicitly discuss edge cases like all land or all water to show thoroughness.
Check if there is any land or any water in the grid. If either is missing, return -1 immediately.
Create a queue and enqueue all land cells with distance 0. Initialize a distance matrix with -1 for unvisited cells.
While the queue is not empty, pop a cell and explore its four neighbors. If a neighbor is water and unvisited, set its distance to current distance + 1 and enqueue it.
During BFS, keep track of the maximum distance assigned to any water cell. After BFS, return this maximum.
State that time complexity is O(n^2) since each cell is processed once, and space complexity is O(n^2) for the queue and distance matrix.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.