828. Count connected regions in a binary grid
Segmentation masks, occupancy maps and game boards are often stored as grids of 0 and 1. A common first step is to count how many separate regions of 1 cells there are.
Write count_islands(grid). grid is a list of equal-length strings made of '1' (land) and '0' (water). Two land cells belong to the same island if they touch up, down, left or right (not diagonally). Return the number of islands. An empty grid has 0 islands.
def count_islands(grid)Example 1
Input: count_islands(['110', '010', '001'])
Output: 2
Example 2
Input: count_islands(['000'])
Output: 0
Constraints
- 0 <= rows, cols <= 1,000
- Cells are only '0' or '1'
Hint 1
Keep a seen matrix the same size as the grid.
Hint 2
Only start a fill from land that is not seen yet.
Hint 3
Mark cells as seen when you push them.
Common mistakes
- Counting diagonal neighbours as connected.
- Recursing deeply and hitting the recursion limit on big grids.
- Forgetting the empty-grid case.
Understand the idea
Connected-component labelling turns a grid into a graph and floods each component once. For ['110', '010', '001'] the fill starting at (0, 0) marks (0, 1) and (1, 1), so the first island has three cells; (2, 2) starts a second island. Total work is O(rows x cols) because every cell is marked once.