You are given an m x n binary grid representing a black-and-white image, where 1 is a filled pixel and 0 is empty. A pixel island is a group of 1s connected 4-directionally (horizontally or vertically).
Return the number of distinct pixel islands in the grid. Two cells belong to the same island if you can travel between them by moving up, down, left, or right through cells that contain 1.
Function Signature
def count_islands(grid: list[list[int]]) -> int:
Rules
-
grid
is a list of rows, and every row has the same length.
-
Cells that touch only at a corner are not connected.
-
Positions outside the grid count as empty.
Constraints
-
1 <= m, n <= 300
, where
m = len(grid)
and
n = len(grid[0])
-
grid[i][j]
is
0
or
1
.
Examples
Input: grid = [
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 1]
]
Output: 3
The islands are the 2x2 block in the top-left, the single pixel in the middle, and the horizontal pair in the bottom-right. The middle pixel at (2, 2) touches the block only at the corner (1, 1) and the pair only at the corner (3, 3), so all three stay separate.
Input: grid = [
[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
]
Output: 1
All the 1s form one island. The pixel at row 1, column 3 connects upward to the top row, and the block in the first two columns connects to the top row as well.
Input: grid = [
[1, 0],
[0, 1]
]
Output: 2
The two filled pixels touch only diagonally, so each is its own island.