Use a graph traversal algorithm like BFS or DFS to explore each unvisited land cell, marking all connected land cells as part of the same island. Iterate through the grid, and for each unvisited land cell, increment the island count and perform a traversal to mark the entire island.
Pro tip: Clarify whether diagonal connections count as part of the same island; if not, ensure your traversal only considers four directions. Also, discuss trade-offs between BFS and DFS, and consider iterative DFS to avoid recursion depth issues on large grids.
Confirm that islands are defined by 4-directional connectivity and that you need to count distinct groups of land cells. Ask about grid size and constraints to choose the right approach.
Decide between BFS (using a queue) or DFS (using recursion or a stack). BFS is often safer for large grids due to recursion limits, but DFS is simpler to code.
Loop through each cell. When you find an unvisited land cell, increment the island count and start a traversal to mark all connected land cells as visited.
During traversal, mark cells as visited either by modifying the grid in-place (e.g., changing '1' to '0') or using a separate visited matrix to avoid revisiting.
State that time complexity is O(rows * cols) since each cell is visited once, and space complexity is O(min(rows, cols)) for BFS queue or O(rows * cols) for DFS recursion stack in worst case.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.