Treat the grid as a graph and use DFS/BFS to explore each connected component of land. Iterate through each cell; when you find an unvisited '1', increment the count and traverse all connected land cells, marking them as visited to avoid recounting.
Pro tip: Mention that you can optimize space by modifying the grid in-place (e.g., setting visited land to '0') if allowed, and discuss trade-offs between DFS (recursion depth risk) and BFS (queue memory).
Restate the problem to ensure understanding: count connected components of '1's using 4-directional adjacency. Ask about grid size limits, mutability, and edge cases (empty grid, all water, all land).
Decide between DFS (recursive or iterative) and BFS. Consider constraints: DFS recursion may cause stack overflow for large grids; BFS uses a queue but avoids recursion limits.
Iterate through each cell. When encountering an unvisited '1', increment the island count and perform DFS/BFS to mark all connected land cells as visited (e.g., set to '0' or use a visited matrix).
During traversal, check for out-of-bounds indices and only move in four directions (up, down, left, right). Ensure water cells are skipped.
State time complexity O(M×N) and space complexity O(M×N) in worst case (e.g., all land). Walk through edge cases and test with a small example.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.