Count Connected Land Regions in a Binary Grid
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests iterative 2D graph traversal to count connected components of land cells without modifying the input or risking recursion stack overflow.
Problem Statement
You are given an m x n binary grid map_grid made up of 1s (land) and 0s (water). Two land cells are part of the same region if they are directly adjacent horizontally or vertically. Your task is to count and return the total number of distinct land regions in the grid.
Two important rules govern your implementation:
- Read-only input. The grid must be in exactly the same state when your function returns as it was when it was called. Overwriting cells to track visited positions is not allowed.
- No deep recursion. On very large grids a recursive flood fill can exhaust Python's call stack. Your solution must use an iterative traversal instead.
Constraints
m == len(map_grid)n == len(map_grid[i])1 <= m, n <= 1000map_grid[i][j]is either0or1(integer)- The grid must be unchanged after your function returns
Examples
Example 1
Input: count_land_regions([[1, 1, 0], [1, 0, 0], [0, 0, 1]])
Output: 2
Example 2
Input: count_land_regions([[1, 1, 1], [0, 0, 0], [1, 1, 1]])
Output: 2
Hints
Hint 1
Think of every land cell as a node in a graph. Two nodes share an edge when they are direct horizontal or vertical neighbors. Counting land regions is the same problem as counting connected components in that graph.
Hint 2
Since you cannot mark visited cells by writing into the grid, keep a separate flat bytearray of size m * n. Representing each cell as a single integer index (row * cols + col) lets you use cheap integer arithmetic instead of allocating coordinate tuples.
Hint 3
Replace the recursive flood fill with an explicit stack (or queue). Push a cell's flat index when you first mark it visited, then pop and expand its up to four neighbors. This keeps the call stack flat regardless of how large or oddly shaped a region is.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Treat the grid as an implicit graph: each land cell is a node, and an edge exists between two nodes when they occupy directly adjacent cells (up, down, left, right). Counting land regions is identical to counting connected components in that graph.
The standard technique is flood fill: scan every cell in row-major order; whenever you land on a land cell that has not been visited yet, you have discovered a new region — increment the counter and immediately explore every cell reachable from it, marking each one visited so it never triggers another count.
Handling the two constraints
Read-only input. The usual shortcut of setting a visited land cell to 0 is ruled out. Instead, a flat bytearray of size m * n tracks visits externally. Cell (r, c) maps to index r * cols + c. A bytearray costs 1 byte per cell — roughly 1 MB at the maximum grid size — compared with ~8 bytes per entry for a Python list of booleans or much more for a set of coordinate tuples.
No deep recursion. A 1 000 × 1 000 all-land grid would require a call depth of up to 10⁶, far beyond Python's default limit. An explicit stack replaces the call stack: push a cell's flat index when it is first marked visited, then pop and expand neighbors iteratively. Cells are marked visited on push, not on pop, which guarantees each cell enters the stack at most once.
Why the count is exact
- Every region is counted at least once: the outer scan touches every cell, and the first cell of any region in scan order cannot have been visited by an earlier traversal (a traversal only marks cells in its own component).
- Every region is counted at most once: after the traversal from a starting cell finishes, every land cell reachable from it is marked visited, so the scan silently skips all of them.
Edge cases
| Situation | Behavior |
|---|---|
| Empty grid or empty rows | Early guard returns 0 |
| No land cells | Every cell fails the == 1 check; result is 0 |
| Entirely land | One traversal covers everything; result is 1 — the case that breaks recursive solutions |
| Single row or column | Boundary checks (cr > 0, cc + 1 < cols, etc.) handle degenerate shapes naturally |
Diagonal-only contact, e.g. [[1,0],[0,1]] | Diagonals are never explored; result is 2 |
Complexity
- Time: O(m · n). The outer loop visits each cell once. Each land cell is pushed and popped at most once; each pop inspects four neighbors in O(1).
- Space: O(m · n). The
visitedbytearray ism * nbytes. The stack holds at most O(m · n) entries in the worst case (an all-land grid). No call-stack growth because there is no recursion.
Implementation notes
Storing flat integer indices on the stack instead of (row, col) tuples avoids allocating a Python tuple object per cell — a meaningful constant-factor saving on million-cell grids. The four neighbor directions are written out explicitly for the same reason. Both are optimizations, not requirements; a clean BFS with a direction list is equally correct.
from typing import List
def count_land_regions(map_grid: List[List[int]]) -> int:
if not map_grid or not map_grid[0]:
return 0
rows, cols = len(map_grid), len(map_grid[0])
# One byte per cell; flat index for cell (r, c) is r * cols + c.
# Avoids modifying the input and is far more compact than a set of tuples.
visited = bytearray(rows * cols)
regions = 0
for r in range(rows):
for c in range(cols):
start = r * cols + c
if map_grid[r][c] != 1 or visited[start]:
continue
# First encounter with an unvisited land cell — new region found.
regions += 1
visited[start] = 1
stack = [start]
while stack:
cell = stack.pop()
cr, cc = divmod(cell, cols)
# Up
if cr > 0:
neighbor = cell - cols
if map_grid[cr - 1][cc] == 1 and not visited[neighbor]:
visited[neighbor] = 1
stack.append(neighbor)
# Down
if cr + 1 < rows:
neighbor = cell + cols
if map_grid[cr + 1][cc] == 1 and not visited[neighbor]:
visited[neighbor] = 1
stack.append(neighbor)
# Left
if cc > 0:
neighbor = cell - 1
if map_grid[cr][cc - 1] == 1 and not visited[neighbor]:
visited[neighbor] = 1
stack.append(neighbor)
# Right
if cc + 1 < cols:
neighbor = cell + 1
if map_grid[cr][cc + 1] == 1 and not visited[neighbor]:
visited[neighbor] = 1
stack.append(neighbor)
return regions