Count Islands in a Binary Grid
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Count four-directionally connected islands in a potentially large binary grid without changing the caller's input. The problem emphasizes complete graph traversal, empty and narrow grids, and avoiding recursive stack overflow on long components.
Constraints
- 0 <= len(grid) <= 2000.
- When nonempty, all rows have equal length and 1 <= len(grid[0]) <= 2000.
- The grid contains at most 2000000 cells, each equal to 0 or 1.
- Only horizontal and vertical edges connect land cells.
Examples
Input: (['11000', '11010', '00100', '00011'],)
Expected Output: 4
Explanation: Four separate four-neighbor components are present.
Input: ([],)
Expected Output: 0
Explanation: An empty grid contains no islands.
Hints
- Starting a traversal from each unseen land cell counts one new connected component.
- Mark a neighbor when adding it to the worklist so it is not added twice.