Clarify that the grid is n x n and islands are 4-directionally connected. Then propose a graph traversal (DFS or BFS) that scans the grid and, upon finding an unvisited '1', increments the count and explores the entire island, marking cells as visited. Discuss complexity and possible optimizations like union-find or iterative BFS to avoid recursion limits.
Pro tip: At Amazon, emphasize scalability and edge cases: mention that for very large grids, an iterative BFS or union-find avoids recursion depth issues, and always clarify whether diagonal connections count. Also, note that modifying the input grid to mark visited cells saves space but may not be allowed—ask if mutation is acceptable.
Confirm grid dimensions, connectivity (4-directional vs 8-directional), and whether the input can be mutated. Ask about edge cases like empty grid or all 1s.
Decide between DFS (recursive or iterative) and BFS. For Amazon, mention trade-offs: DFS is simpler but recursion may overflow; BFS uses a queue and is safer for large grids.
Iterate through each cell. When a '1' is found, increment island count and perform traversal to mark all connected '1's as visited (e.g., set to '0' or use a visited matrix).
State time complexity O(n^2) since each cell is visited once, and space complexity O(n^2) in worst case for recursion/queue or visited matrix.
Mention union-find as an alternative with near-linear time, or using BFS to avoid recursion limits. Also, note that if mutation is allowed, space can be O(1) extra.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.