Connected Land Regions on a Grid (8-Direction)
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests graph traversal skills by counting connected components in a character grid where land cells are neighbours in all eight directions including diagonals.
Connected Land Regions on a Grid
You have an m × n grid where every cell holds either '1' (land) or '0' (water). Two land cells belong to the same region if you can walk from one to the other through a chain of land cells, stepping in any of the eight compass directions — that is, horizontally, vertically, or diagonally adjacent.
Return the total number of distinct land regions in the grid.
Details
- A single isolated land cell is its own region.
- A diagonal step counts as a valid connection. A cell at
(r, c)can reach up to eight neighbours:(r±1, c),(r, c±1), and(r±1, c±1). - Water cells (
'0') are never part of any region and cannot be crossed. - An empty grid (no rows, or rows of length zero) contains zero regions.
Constraints
0 ≤ m, n ≤ 300- Every cell is either
'1'or'0' - Rows are not necessarily the same length as columns (the grid can be non-square)
- You may not modify the input grid
Examples
Example 1
Input: count_land_regions([['1', '1', '0', '0'], ['0', '1', '0', '1'], ['0', '0', '1', '0']])
Output: 1
Example 2
Input: count_land_regions([['1', '0', '0'], ['0', '1', '0'], ['0', '0', '1']])
Output: 1
Example 3
Input: count_land_regions([['0', '0', '0'], ['0', '0', '0']])
Output: 0
Hints
Hint 1
Think of each land cell as a node and each pair of adjacent (including diagonal) land cells as an edge. The answer is the number of connected components in that graph. How would you count connected components efficiently?
Hint 2
Each time your outer scan finds an unvisited land cell, you have discovered a new region. A flood-fill from that cell — iterative DFS with an explicit stack, or BFS with a deque — can mark every cell in the same region as visited before you continue scanning. What data structure will you use to track visited cells?
Hint 3
A subtle but important detail: mark a cell as visited the moment you add it to the stack or queue, not when you remove it. If you wait until pop/dequeue, the same cell can be added multiple times by up to eight different neighbours, bloating your stack and wasting work.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Model the grid as an implicit graph: every '1' cell is a node, and two nodes share an edge when their cells are adjacent in any of the eight directions. The answer is the number of connected components among land nodes.
The standard way to count connected components is a flood-fill scan:
- Iterate over every cell in row-major order.
- When you hit a land cell that has not yet been visited, you have found a new component. Increment the counter.
- From that starting cell, run a traversal that marks every reachable land cell as visited.
- Resume the scan. Previously absorbed cells are skipped automatically.
Why iterative DFS
The reference solution uses an explicit stack rather than recursion. A fully recursive DFS is natural to write, but Python's default call-stack limit is around 1 000 frames. A grid that is entirely land can produce a recursion depth of m × n, which overflows that limit on grids as small as 32 × 32. An explicit stack lives on the heap and is bounded only by available memory, so it scales without any sys.setrecursionlimit hacks.
Why mark on push, not on pop
When a cell is popped, each of its up to eight neighbours can independently add it back to the stack if it has not yet been marked. In the worst case the same cell is enqueued eight times. Marking a cell as visited the instant it is pushed prevents all duplicate entries and keeps both stack size and total work proportional to the number of land cells.
Correctness
- Every land cell is reached by the outer scan, so no component is missed.
- Once a cell is visited, the outer loop skips it, so no component is counted twice.
- The traversal only crosses land cells, so it cannot jump over water into a separate component.
The eight-direction neighbourhood is what separates this problem from the classic four-direction version. A diagonal-only connected pattern — for example, '1's on the main diagonal of an otherwise-water grid — forms one region here, but would be counted as entirely separate single-cell regions under four-direction rules.
Complexity
Let m = number of rows, n = number of columns.
- Time: O(m · n). The outer scan visits each cell once. Every land cell is pushed and popped at most once. Each pop inspects a constant eight neighbours.
- Space: O(m · n). The
visitedmatrix takesm · nbytes (usingbytearrayfor compactness). The stack can hold at mostm · nentries in the pathological case of an all-land grid.
If mutating the input were allowed, you could overwrite visited land cells with '0' and drop the visited matrix entirely, reducing extra space to O(m · n) for the stack only (O(1) auxiliary storage beyond the stack). The problem statement forbids mutation here, so we keep the separate matrix.
Reference solution
from typing import List
def count_land_regions(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
# bytearray is more memory-efficient than a list of Python bools
visited = [bytearray(cols) for _ in range(rows)]
# All eight compass directions
directions = (
(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1),
)
regions = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or visited[r][c]:
continue
# Found the first cell of a new region
regions += 1
visited[r][c] = 1
stack = [(r, c)]
# Iterative DFS — avoids Python recursion-depth limits
while stack:
cur_r, cur_c = stack.pop()
for dr, dc in directions:
nr, nc = cur_r + dr, cur_c + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and not visited[nr][nc]
and grid[nr][nc] == '1'
):
# Mark on push, not on pop, to prevent duplicate entries
visited[nr][nc] = 1
stack.append((nr, nc))
return regions