Use a graph traversal algorithm (DFS or BFS) to explore each unvisited land cell, marking all connected land cells as visited to count one island. Iterate through the grid, and for each unvisited '1', increment the island count and perform a traversal to mark the entire island.
Pro tip: Discuss the trade-offs between DFS and BFS, especially regarding stack overflow risks with DFS on large grids, and mention that you can modify the grid in-place to save space if allowed. Also, clarify assumptions about grid boundaries and connectivity (4-directional vs 8-directional).
Confirm the definition of an island (4-directional connectivity), input constraints (grid size, mutability), and expected output (integer count).
Decide between DFS (recursive or iterative) and BFS, considering space complexity and potential stack overflow. Explain your choice.
Write a function that, given a starting cell, explores all connected land cells and marks them as visited (e.g., set to '0' or use a visited set).
Loop through each cell in the grid; when an unvisited '1' is found, increment the island count and trigger the traversal to mark the entire island.
State time complexity O(M*N) and space complexity O(M*N) in worst case (e.g., all land), and discuss optimizations if needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.