I went with DFS and it worked fine, but I wasted probably two minutes overthinking whether BFS would be more impressive.
Use DFS or BFS to traverse the grid, counting each unvisited land cell as a new island and marking all connected land cells as visited. Alternatively, use Union-Find to group connected land cells and count distinct sets. Discuss trade-offs between approaches.
Pro tip: Mention that you can optimize space by modifying the grid in-place (e.g., changing '1' to '0') instead of using a separate visited array, but clarify if the input can be mutated. Also, consider iterative DFS to avoid stack overflow for large grids.
Confirm grid dimensions, connectivity (4-directional), and whether the grid can be modified. Ask about edge cases like empty grid or all water.
Select DFS, BFS, or Union-Find based on constraints and preferences. Explain why (e.g., DFS is simple, Union-Find is good for dynamic connectivity).
Iterate through each cell; when encountering unvisited land, increment island count and traverse all connected land cells, marking them visited.
State time complexity O(M*N) and space complexity O(M*N) for visited array or recursion stack, or O(M*N) for Union-Find.
Walk through a small example (e.g., 3x3 grid) to verify the approach and handle edge cases like single cell or diagonal connections.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.