Treat the grid as a graph and use DFS or BFS to explore each unvisited land cell, marking all connected land as visited to count one island. Iterate through every cell, incrementing the island count each time you start a traversal from an unvisited '1'.
Pro tip: Mention that you can mutate the input grid to mark visited cells (e.g., set to '0') to save space, but clarify that if the input must be preserved, use a separate visited set. This shows awareness of trade-offs and real-world constraints.
Restate the problem to ensure understanding: count connected components of '1's using 4-directional adjacency. Ask about edge cases like empty grid, large input, or if diagonal connections count.
Decide between DFS (recursive or iterative) and BFS. Discuss trade-offs: DFS is simpler but may cause stack overflow on large grids; BFS uses a queue and avoids recursion depth issues.
Iterate through each cell. When a '1' is found, increment island count and perform DFS/BFS 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) in worst case for recursion stack or queue.
Walk through a small example, consider edge cases (all water, all land, single row/column). Mention possible optimizations like union-find for dynamic scenarios.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.