Count Land Cells in a Connected Region
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests iterative graph traversal (DFS/BFS) on a binary grid, including bounds handling, visited-marking strategy, and complexity analysis.
Count Land Cells in a Connected Region
You are given an m x n binary grid where each cell holds either 0 (water) or 1 (land). Two land cells belong to the same region if you can travel between them using only up, down, left, and right steps — diagonal moves do not count.
Write a function count_region(grid, row, col) that returns the number of land cells in the region that contains the cell at position (row, col).
Return 0 if any of the following apply:
gridis empty.(row, col)is outside the grid boundaries (including negative indices).- The cell at
(row, col)is water.
You may modify the grid in place to track which cells have already been visited, or you may use a separate data structure — whichever you choose, be prepared to explain the trade-off.
Constraints
0 <= m, n <= 1000(grid may be empty)- Every cell value is
0or1 rowandcolmay be any integer, including negative values- 4-directional connectivity only (up, down, left, right)
- A single isolated land cell has a region size of
1 - If the function is called twice on the same region and the grid is mutated, the second call returns
0
Examples
Example 1
Input: count_region([[1, 1, 0], [0, 1, 0], [1, 0, 1]], 0, 0)
Output: 3
Example 2
Input: count_region([[1, 1, 0], [0, 1, 0], [1, 0, 1]], 2, 0)
Output: 1
Example 3
Input: count_region([[0, 1], [1, 1]], 0, 0)
Output: 0
Hints
Hint 1
Before indexing into the grid, explicitly check that row and col are both non-negative and within bounds — Python's negative indexing will silently wrap around and give you the wrong answer.
Hint 2
Mark each cell as visited the moment you push it onto the stack, not when you pop it. Marking on pop lets the same cell get pushed multiple times by different neighbors, which inflates the count.
Hint 3
Recursive DFS is elegant but risky here: a 1000×1000 all-land grid would require a million recursive calls, well past Python's default limit. An explicit stack on the heap gives you the same traversal order without that risk.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The grid is essentially an undirected graph: each land cell is a node, and an edge connects two land cells that are 4-directional neighbors. The region containing (row, col) is the connected component of that node. Counting its size means visiting every reachable land cell exactly once.
Algorithm: Iterative DFS
- Validate inputs. Return
0for an empty grid, for any out-of-bounds or negative index, or if the starting cell is water. - Seed the traversal. Push
(row, col)onto a stack and immediately mark it visited by settinggrid[row][col] = 0. - Expand. On each iteration, pop a cell, increment the counter by 1, then inspect all four neighbors. Any in-bounds neighbor that is still
1gets set to0and pushed. - Finish. When the stack empties, every cell in the region has been counted.
Why an explicit stack instead of recursion?
Python's default recursion limit is around 1000. A 1000×1000 all-land grid would require up to one million recursive frames, which crashes immediately. An explicit stack uses the same depth-first logic but allocates frames on the heap, sidestepping the limit entirely.
Marking on push, not on pop
Each cell is set to 0 at the moment it is added to the stack. If you waited until pop, multiple neighbors could independently discover and push the same cell before it is processed, causing it to be counted more than once. Marking on push guarantees each cell enters the stack at most once.
Mutation trade-off
Setting visited cells to 0 is an O(1)-per-cell visited tracker with no extra memory. The downside is that the caller's grid is permanently altered. If the original grid must be preserved, use a separate visited set or an m × n boolean matrix — both cost O(m·n) additional space in the worst case.
Correctness
- Every counted cell belongs to the region. A cell is pushed only when it is land and adjacent to a cell already known to be in the region. By induction, everything reachable from the start is in the same connected component.
- No cell is missed. For any land cell connected to
(row, col)by a path, each cell on the path is either already marked or will be pushed when the previous cell on the path is popped. The traversal reaches the entire path. - No double counting. A cell is pushed only while it equals
1, and it is set to0at that instant. It is therefore pushed, and later popped and counted, exactly once.
Edge Cases
grid = []orgrid = [[]]→ return0.- Negative
roworcol→ return0(checked explicitly before indexing). - Starting cell is a single isolated land cell → return
1. - All-land grid → return
m * n; this is also the case that breaks recursive DFS. - Diagonal neighbors only (e.g.,
[[1,0],[0,1]]queried at(0,0)) → return1, since diagonals are not connected.
Complexity
| Value | |
|---|---|
| Time | O(k), where k is the region size; O(m·n) worst case |
| Space (stack) | O(k) worst case |
| Space (visited) | O(1) extra when mutating the grid |
Reference Solution
from typing import List
def count_region(grid: List[List[int]], row: int, col: int) -> int:
# Handle empty grid
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
# Explicit bounds check — must come before indexing to catch negatives
if row < 0 or row >= m or col < 0 or col >= n or grid[row][col] != 1:
return 0
# Iterative DFS: mark cells as visited (set to 0) on push, not on pop
stack = [(row, col)]
grid[row][col] = 0
size = 0
while stack:
x, y = stack.pop()
size += 1
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1:
grid[nx][ny] = 0
stack.append((nx, ny))
return size
Switching to BFS requires only replacing the list with a collections.deque and pop() with popleft(). The count is unaffected by traversal order, so correctness and complexity are identical.