I went with DFS and marked visited cells by flipping them to '0' in place.
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 traversal. Alternatively, use Union-Find to group connected land cells and count distinct sets. The key is to systematically visit each cell and avoid revisiting.
Pro tip: Clarify edge cases upfront (empty grid, all water, all land) and discuss trade-offs between DFS (recursive, risk of stack overflow) and BFS (iterative, uses queue) or Union-Find (efficient for dynamic connectivity). Mentioning these shows depth and prevents follow-up pitfalls.
Confirm grid dimensions, connectivity definition (4-directional), and whether diagonal connections count. Ask about input constraints (size, memory) and expected output.
Select DFS, BFS, or Union-Find based on constraints. For most interviews, DFS/BFS is straightforward; Union-Find is elegant for large grids or streaming data.
Iterate through each cell; when encountering an unvisited '1', increment island count and launch a traversal to mark all connected '1's as visited (e.g., set to '0' or use a visited matrix).
State time complexity O(M×N) since each cell is visited once, and space complexity O(M×N) for recursion stack or queue in worst case (all land).
Walk through a small grid (e.g., 3x3) to verify correctness, including edge cases like a single island, multiple islands, and no islands.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.