Count Islands of Connected Land Cells in a Binary Grid
UberSoftware Engineer · OnsiteLast updated
A classic grid coding problem asking you to count the islands formed by horizontally or vertically connected land cells in a binary grid. It tests grid traversal, connected-component counting, and careful handling of grid boundaries and already visited cells.
You are given an m x n grid where 1 is land and 0 is water. An island is a maximal group of land cells connected horizontally or vertically. Return the number of islands in the grid.
Function Signature
def count_islands(grid: list[list[int]]) -> int:
Rules
- Two land cells belong to the same island exactly when one can be reached from the other by moving up, down, left or right through land cells. Diagonal contact does not connect cells.
- Every position outside the grid is water.
- Return
0if the grid has no land.
Constraints
1 <= m, n <= 300, wherem = len(grid)andlen(grid[i]) == nfor every rowi- Every cell is
0or1. - A single island can contain all
m * ncells, and the answer is at mostm * n.
Examples
Example 1
Input: grid = [
[1, 0, 1, 1],
[1, 0, 0, 1],
[0, 1, 0, 0],
[1, 1, 0, 1]
]
Output: 4
The islands are {(0, 0), (1, 0)}, {(0, 2), (0, 3), (1, 3)}, {(2, 1), (3, 0), (3, 1)} and {(3, 3)}. Cells (1, 0) and (2, 1) touch only diagonally, so they are in different islands.
Example 2
Input: grid = [
[1, 1, 1],
[0, 1, 0],
[1, 1, 1]
]
Output: 1
The middle column connects the top and bottom rows into one island.
Example 3
Input: grid = [
[0, 0],
[0, 0]
]
Output: 0
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.