Counting Separate Land Patches in a 0/1 Grid
Trees & GraphsAuto-graded · 20 test casesLast updated
Count connected components of 1-cells in a binary grid using only up/down/left/right adjacency, via flood fill or union-find.
You are given a rectangular grid made up of 0s (water) and 1s (land). A patch is a maximal group of land cells in which any two cells are linked by a chain of land cells, where each step in the chain moves to a cell directly above, below, to the left of, or to the right of the previous one.
Cells that touch only at a corner are not linked.
Return the total number of patches in the grid.
Input
grid: a list of rows, each row a list of integers that are all0or1. All rows have the same length.
Output
- A single integer: the number of patches.
Special cases
- If the grid has no rows, or its rows have no columns, return
0. - If the grid contains no land, return
0.
Constraints
- Every entry of
gridis0or1. - All rows have equal length.
- The grid may be empty (
[]or[[]]), in which case the answer is0. - Large grids (for example, 1000 x 1000 filled entirely with
1) are possible, so avoid unbounded recursion depth. - Do not rely on diagonal adjacency.
Examples
Example 1
Input: count_land_patches([[1, 1, 0], [0, 1, 0], [1, 0, 1]])
Output: 3
Example 2
Input: count_land_patches([[1, 0, 0, 1], [0, 0, 1, 0], [1, 1, 0, 0]])
Output: 4
Example 3
Input: count_land_patches([[1, 1, 1], [0, 1, 0], [0, 0, 0]])
Output: 1
Hints
Hint 1
Think of each land cell as a node, with edges between land cells that share a side. You are counting connected components.
Hint 2
Scan cells in row-major order. Whenever you meet a land cell you have not seen yet, you have found a new patch; then explore everything connected to it and mark it as seen.
Hint 3
Use an iterative traversal (a queue or an explicit stack) rather than deep recursion, and mark a cell as seen when you add it to the queue so it is never added twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the grid as a graph: each land cell is a node, and two land cells are joined by an edge when they share a side. The answer is the number of connected components of this graph.
Scan the grid in row-major order. Each time you reach a land cell that has not been seen, you have found a new patch. Increase the counter and run a breadth-first search from that cell, visiting every land cell reachable by up/down/left/right moves and marking each as seen. Later in the scan, all cells of that patch are skipped.
A separate seen matrix is used so the input grid is not modified. Cells are marked when they are enqueued (not when dequeued), which prevents the same cell from being queued several times.
Why it is correct
- Counted at least once: the first cell of any patch in row-major order is unseen when the scan reaches it, because earlier searches only mark cells in other patches. So a new search starts there.
- Counted at most once: the search from that cell reaches every cell of its patch, marking all of them, so no second search can start inside the same patch.
- Only the four orthogonal offsets are explored, so diagonal contact never merges patches.
Edge cases
[]and[[]]return0due to the initial guard.- A grid of all zeros never starts a search, so the result is
0. - A grid of all ones yields exactly one patch.
- An iterative BFS avoids Python's recursion limit on very large single patches.
Complexity
- Time: O(R * C). Each cell is visited a constant number of times.
- Space: O(R * C) for the
seenmatrix and, in the worst case, the queue.
Reference solution
from collections import deque
from typing import List
def count_land_patches(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
seen = [[False] * cols for _ in range(rows)]
patches = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
patches += 1
seen[r][c] = True
queue = deque([(r, c)])
while queue:
cr, cc = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols:
if grid[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
queue.append((nr, nc))
return patches