I went with DFS, marking cells as visited as I sank them.
Treat the grid as a graph and use DFS or BFS to explore each unvisited land cell, marking all connected land cells as visited to count one island. Iterate through every cell, and when you find an unvisited '1', increment the island count and launch a traversal to mark the entire island.
Pro tip: Mention that you can optimize space by mutating the input grid (e.g., changing '1' to '0') if allowed, but clarify that in production code you'd avoid side effects or use a separate visited set. Also, discuss handling edge cases like empty grid or large grids that could cause stack overflow with recursive DFS.
Confirm grid dimensions, connectivity (4-directional), and whether modifying the input is acceptable. Ask about edge cases like empty grid or all water.
Decide between DFS (recursive or iterative) and BFS. Discuss trade-offs: DFS is simpler but may overflow stack; BFS uses queue and is safer for large grids.
Loop through each cell. When encountering an unvisited '1', 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 is visited once, and space complexity O(M*N) in worst case for recursion stack or queue.
Walk through a small example, test edge cases, and mention potential optimizations like union-find or parallel processing for very large grids.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.