I went with BFS because DFS felt like it might blow the stack on a big grid and I said that out loud which I think was fine.
Treat the grid as a graph and use DFS/BFS to explore each unvisited land cell, marking all connected land cells as visited to count one island. Iterate through every cell, and when an unvisited '1' is found, increment the island count and flood-fill to mark the entire island.
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). Mention that modifying the grid in-place is acceptable if allowed, otherwise use a visited set.
Confirm grid dimensions, whether diagonal connections count (they don't), and if modifying the input is allowed. Discuss edge cases like empty grid or no land.
Decide between DFS (recursive or iterative) and BFS. Explain why one might be preferred (e.g., DFS simpler, BFS avoids recursion depth issues).
Iterate through each cell. When an unvisited '1' is found, increment count and perform traversal to mark all connected land cells as visited (e.g., set to '0' or use visited set).
State time complexity O(M*N) since each cell visited once, and space complexity O(M*N) worst-case for recursion stack or queue.
Walk through a small example to verify correctness, including edge cases like single cell, multiple islands, and no islands.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.