I went with DFS pretty quickly, which was the right call.
Use a graph traversal algorithm (DFS or BFS) to explore each unvisited land cell and mark all connected land cells as visited, incrementing the island count for each new traversal. Alternatively, use Union-Find to group connected land cells and count distinct sets. Discuss trade-offs between approaches.
Pro tip: Clarify whether you can modify the input grid; if not, use a separate visited matrix or Union-Find to avoid mutating data. Also, mention that BFS avoids recursion depth issues for large grids.
Ask about grid dimensions, whether the grid can be modified, and if diagonal connections count. Confirm that only horizontal and vertical connections define an island.
Select between DFS, BFS, or Union-Find based on constraints. For most interviews, DFS is simplest; BFS is safer for large grids; Union-Find is efficient for dynamic connectivity.
Iterate through each cell; when a '1' is found, increment island count and perform traversal to mark all connected '1's as visited (e.g., set to '0' or use a visited set).
State time complexity O(M×N) and space complexity O(M×N) for visited matrix or O(min(M,N)) for BFS queue. Discuss potential optimizations like early termination or iterative deepening.
Walk through a small grid (e.g., 3x3) to verify correctness, including edge cases like all water, all land, and single row/column.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.