Connected Land Regions in a Matrix

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are given an m x n matrix grid whose cells hold either 1 (solid ground) or 0 (open water). Two ground cells belong to the same connected region whenever a path of 1 cells links them using only orthogonal steps — up, down, left, or right. Cells touching only at diagonal corners do not join into a single region.

Implement count_regions(grid: List[List[int]]) -> int to compute how many separate connected ground regions exist in grid (returning 0 when grid is empty or contains only 0s).

Examples

Example 1

Input:
  grid = [
    [1, 0, 1, 1],
    [1, 0, 0, 1],
    [0, 1, 0, 0]
  ]
Output: 3

Walk-through: - (0, 0) and (1, 0) share a vertical edge, forming one 2-cell region on the left. - (0, 2), (0, 3), and (1, 3) connect horizontally and vertically into an L-shaped 3-cell region on the upper right. - (2, 1) meets (1, 0) only diagonally, so it forms a third isolated 1-cell region.

Example 2

Input:
  grid = [
    [0, 1, 0],
    [1, 0, 1],
    [0, 1, 0]
  ]
Output: 4

Walk-through: The four 1 cells at (0, 1), (1, 0), (1, 2), and (2, 1) surround a center 0 and touch only at corners, producing 4 single-cell regions.

Constraints

  • m == len(grid) and n == len(grid[i]) for all 0 <= i < m.
  • 0 <= m, n <= 300 (1 <= m, n <= 300 for non-empty matrices; return 0 if m == 0 or n == 0).
  • Every entry grid[i][j] is 0 or 1.

Step-by-step walkthrough

  1. Understand the problem and 4-directional rule

    We have an m x n matrix of 1s (ground) and 0s (water). Two ground cells belong to the same region when a path of 1s links them through 4-directional moves — up, down, left, or right. Diagonal corners do not merge two regions.

    Example 1 (answer = 3):              Example 2 (answer = 4):
      [1]  0  [1, 1] <- Region B (L-shape)   0  [1]  0
      [1]  0   0 [1]                        [1]  0  [1]   <- touch only at corners:
       ^-- Region A (2x1)                    0  [1]  0       4 separate regions!
       0  [1]  0  0  <- Region C (1x1)
    

    Empty inputs ([] or [[]]) contain zero cells and return 0.

  2. Why a local row-by-row check is not enough

    Suppose you tried to count regions in a single top-to-bottom scan by starting a new count whenever a 1 has water above it and to its left. Look at what happens on a U-shaped island:

    Row 0:   1   0   1    <- left arm and right arm look like 2 separate regions!
    Row 1:   1   0   1
    Row 2:   1   1   1    <- bottom row bridges both arms into 1 single region
    

    Two cells in row 0 can connect via a path that dips downward and turns back up many rows later. Instead, model the ground cells as vertices of a graph whose edges connect orthogonally neighboring 1s: each region is one connected component (a maximal set of ground cells mutually reachable from one another).

  3. Key idea: scan the matrix and flood-fill each unseen island

    Walk over every coordinate (row, col) in row-major order while maintaining a seen boolean matrix of visited ground cells:

    1. If a cell is water (0) or already seen, skip past it.
    2. If a cell is unseen ground (1), we have just stepped onto a brand-new region:
      • Increment regions += 1.
      • Flood-fill outward from (row, col) (visiting orthogonal 1 neighbors, their 1 neighbors, and so on) to mark every cell of that island seen = True.

    When our outer loop later reaches the remaining cells of that island, seen is already True, so each region is counted exactly once. (Overwriting visited 1s with 0 in grid would avoid allocating seen, whereas keeping seen preserves the caller's matrix.)

  4. Code iterative DFS with an explicit stack

    How should we run the flood fill? Depth-First Search (DFS) follows connected branches using a stack. Writing DFS recursively is tempting, but on a 300 x 300 matrix (90,000 cells), a single winding path can stretch 45,000+ steps — far exceeding Python's default ~1,000-frame call stack limit and raising RecursionError.

    Using an explicit Python list stack = [(start_row, start_col)] performs the exact same traversal on heap memory without touching Python's call stack. Two details keep mark_region bug-free and linear: - Check bounds before indexing grid[next_row][next_col]: In Python, grid[-1] does not fail — it wraps around to the bottom row! - Set seen[next_row][next_col] = True immediately upon pushing, not when popping. Otherwise, inside a 2 x 2 block of 1s, (1, 1) gets pushed twice before being popped, duplicating work on dense matrices.

    # DIRECTIONS: (row_delta, col_delta) for up, down, left, right (4-directional adjacency only).
    DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    
    
    def mark_region(
        grid: List[List[int]],
        seen: List[List[bool]],
        start_row: int,
        start_col: int,
    ) -> None:
        # Iterative DFS with an explicit stack avoids Python's ~1000-frame recursion limit on 300x300 snakes.
        # stack: list of (row, col) land coordinates belonging to this region waiting to expand.
        rows = len(grid)
        cols = len(grid[0])
        seen[start_row][start_col] = True
        stack = [(start_row, start_col)]
    
        while stack:
            row, col = stack.pop()
            for d_row, d_col in DIRECTIONS:
                next_row = row + d_row
                next_col = col + d_col
                in_bounds = 0 <= next_row < rows and 0 <= next_col < cols
                # Check bounds BEFORE indexing grid[next_row][next_col] so negative indices never wrap around.
                if in_bounds and grid[next_row][next_col] == 1 and not seen[next_row][next_col]:
                    # Mark seen immediately upon push so multiple neighbors never push the same cell twice.
                    seen[next_row][next_col] = True
                    stack.append((next_row, next_col))
    
  5. Write the outer region counter

    In count_regions, guard against [] and [[]] up front, allocate seen with [[False] * cols for _ in range(rows)] so every row is an independent list (never [[False] * cols] * rows, which aliases every row to the same list!), and run the outer scan:

    def count_regions(grid: List[List[int]]) -> int:
        # Phase 1: Guard against empty grids ([] or [[]]) before reading grid[0].
        if not grid or not grid[0]:
            return 0
    
        rows = len(grid)
        cols = len(grid[0])
        # seen: m x n boolean matrix tracking which land cells already belong to a counted region.
        seen = [[False] * cols for _ in range(rows)]
        regions = 0
    
        # Phase 2: Scan every cell once; each unvisited '1' discovers one brand-new connected region.
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == 1 and not seen[row][col]:
                    regions += 1
                    mark_region(grid, seen, row, col)
    
        return regions
    
  6. Trace Example 1 step by step

    Matrix:                   Outer scan events:
      (0,0)=1  0  (0,2)=1 (0,3)=1   1. At (0,0): unseen '1' -> regions = 1
      (1,0)=1  0    0     (1,3)=1      stack=[(0,0)] -> pop (0,0), push & mark (1,0)
        0    (2,1)=1 0      0          pop (1,0) -> (2,1) is diagonal, not orthogonal! -> stack=[]
                                    2. At (0,2): unseen '1' -> regions = 2
                                       stack=[(0,2)] -> push & mark (0,3) -> push & mark (1,3) -> stack=[]
                                    3. At (0,3), (1,0), (1,3): already seen -> skipped!
                                    4. At (2,1): unseen '1' -> regions = 3
                                       all 4 orthogonal neighbors are '0' -> stack=[]
                                    Return: 3
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    # DIRECTIONS: (row_delta, col_delta) for up, down, left, right (4-directional adjacency only).
    DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    
    
    def mark_region(
        grid: List[List[int]],
        seen: List[List[bool]],
        start_row: int,
        start_col: int,
    ) -> None:
        # Iterative DFS with an explicit stack avoids Python's ~1000-frame recursion limit on 300x300 snakes.
        # stack: list of (row, col) land coordinates belonging to this region waiting to expand.
        rows = len(grid)
        cols = len(grid[0])
        seen[start_row][start_col] = True
        stack = [(start_row, start_col)]
    
        while stack:
            row, col = stack.pop()
            for d_row, d_col in DIRECTIONS:
                next_row = row + d_row
                next_col = col + d_col
                in_bounds = 0 <= next_row < rows and 0 <= next_col < cols
                # Check bounds BEFORE indexing grid[next_row][next_col] so negative indices never wrap around.
                if in_bounds and grid[next_row][next_col] == 1 and not seen[next_row][next_col]:
                    # Mark seen immediately upon push so multiple neighbors never push the same cell twice.
                    seen[next_row][next_col] = True
                    stack.append((next_row, next_col))
    
    
    def count_regions(grid: List[List[int]]) -> int:
        # Phase 1: Guard against empty grids ([] or [[]]) before reading grid[0].
        if not grid or not grid[0]:
            return 0
    
        rows = len(grid)
        cols = len(grid[0])
        # seen: m x n boolean matrix tracking which land cells already belong to a counted region.
        seen = [[False] * cols for _ in range(rows)]
        regions = 0
    
        # Phase 2: Scan every cell once; each unvisited '1' discovers one brand-new connected region.
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == 1 and not seen[row][col]:
                    regions += 1
                    mark_region(grid, seen, row, col)
    
        return regions
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine looking down at a pixel map of islands (1) and water (0), holding a dropper of dye that spreads across touching up, down, left, and right ground tiles while stopping at water and diagonal corners. As you scan the map tile by tile and squeeze one drop onto every undyed ground tile you encounter, that drop floods across the entire connected island — a graph traversal technique called flood fill (implemented here via iterative Depth-First Search, or DFS, which expands connected neighbors using a last-in-first-out stack) — so the count of drops squeezed equals the island count.

Why do simpler approaches fall short? Counting islands in one top-to-bottom scan that checks only the neighbor above and to the left miscounts U-shaped islands, whose two upper arms appear disconnected until a bottom row bridges them later. Recursive DFS handles connectivity on small inputs, yet on a 300 x 300 matrix (90,000 cells) a winding path can run 45,000+ cells deep, crashing Python's ~1,000-frame call stack with RecursionError — whereas an explicit stack list lives on heap memory and scales effortlessly.

Here is how the scan processes Example 1 ([[1, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 0]]):

Matrix: (0,0)=1  (0,1)=0  (0,2)=1  (0,3)=1
        (1,0)=1  (1,1)=0  (1,2)=0  (1,3)=1
        (2,0)=0  (2,1)=1  (2,2)=0  (2,3)=0

1. Visit (0,0)=1 (unseen) -> regions = 1; DFS marks (0,0) and (1,0) as seen.
2. Visit (0,2)=1 (unseen) -> regions = 2; DFS marks (0,2), (0,3), and (1,3) as seen.
3. Skip (0,3), (1,0), (1,3) (already seen) and all 0 cells.
4. Visit (2,1)=1 (unseen; touches (1,0) only diagonally!) -> regions = 3; DFS marks (2,1).
Result: 3 regions.

Complexity

  • Time: O(m * n), for m rows and n columns. The outer loop checks each of the m * n cells once, and because every ground cell is marked seen = True as soon as it enters stack, each cell is pushed and popped at most once across the entire call, doing 4 constant-time neighbor checks when popped.
  • Space: O(m * n). The seen table holds m * n booleans, and in the worst case stack stores O(m * n) coordinates simultaneously. (Overwriting visited 1s with 0 inside grid removes seen, though worst-case stack memory remains O(m * n).)

Edge cases

  • Empty matrix ([] or [[]]): Caught immediately by if not grid or not grid[0]:, returning 0 without IndexError.
  • All water ([[0, 0], [0, 0]]): mark_region never runs and 0 is returned.
  • Single cell ([[1]] or [[0]]): Returns 1 for ground and 0 for water.
  • All ground (300 x 300 of 1s): The very first flood fill marks all 90,000 cells and returns 1.
  • Diagonal-only neighbors (Example 2): Diagonal offsets are absent from DIRECTIONS, so the 4 corner-touching 1s stay 4 separate regions.
  • Long winding snake (45,000+ cells on 300 x 300): Explicit stack finishes cleanly without RecursionError.
  • Island inside a lake inside a ring island: Water blocks the outer flood fill, leaving the inner island unseen until the scan reaches and counts it separately.

Common mistakes

  • Using recursive DFS without accounting for Python's recursion limit: On a 300 x 300 serpentine island, recursion depth reaches ~45,000 and raises RecursionError.
  • Marking seen on pop instead of on push: Delaying seen[r][c] = True until stack.pop() lets multiple neighbors push duplicate copies of (r, c) onto stack, inflating memory and runtime on dense matrices.
  • Forgetting 0 <= next_row and 0 <= next_col before indexing: In Python, grid[-1][col] is valid syntax that reads the last row, falsely connecting islands across opposite edges of the matrix!
  • Allocating seen with [[False] * cols] * rows: Multiplying the outer list makes every row point to the same inner list object, so marking (0, 2) marks column 2 in every row. Always write [[False] * cols for _ in range(rows)].
  • Including diagonal offsets in DIRECTIONS: Adding (+-1, +-1) merges corner-touching cells and returns 1 instead of 4 on Example 2.

Alternative approaches

  • Breadth-First Search (BFS): Replace stack.pop() with queue.popleft() on a collections.deque (expanding cells in concentric distance rings rather than deep paths). Runtime stays O(m * n) while worst-case queue size drops to O(min(m, n))!
  • Union-Find (Disjoint-Set Union): A parent-pointer structure supporting find (with path compression) and union in nearly O(1) amortized time per step. Union each 1 cell with its right and bottom 1 neighbors, then count distinct component roots.

Follow-up questions

  • What changes if cells touching diagonally (8-directional adjacency) also merge into the same region? Extend DIRECTIONS from 4 orthogonal pairs to all 8 surrounding offsets by adding (-1, -1), (-1, 1), (1, -1), and (1, 1). Every other line of mark_region and count_regions stays unchanged, and both time and space remain O(m * n) (8 neighbor checks per ground cell instead of 4, merging Example 2's four diamond cells into 1 single region).
  • How do the runtime and auxiliary memory scale with the matrix dimensions m and n? Runtime scales as O(m * n) because the outer loops inspect all m * n cells once and each 1 cell enters and leaves stack at most once with O(1) work per neighbor. Auxiliary memory scales as O(m * n) for the m x n seen table plus O(m * n) worst-case stack depth (switching to BFS with collections.deque and mutating grid in place lowers auxiliary memory to O(min(m, n))).
  • Suppose the matrix resides on disk and cannot fit in RAM—how could you count regions by streaming rows or processing fixed-size tiles? Use Union-Find (a parent-pointer table tracking and merging component IDs) while streaming one row at a time in O(n) RAM: give each 1 in the current row either its left neighbor's ID (when left is 1) or a fresh ID (regions += 1), and whenever the cell directly above in prev_row is also 1 with a different root ID, union the two roots and decrement regions -= 1. After finishing each row, rewrite cur_row labels to their canonical roots and drop all parent entries absent from cur_row so memory stays O(n). For 2D disk tiles (B x B blocks), count internal regions inside each tile independently, retain only the component IDs along each tile's 4 borders (O(B) memory per tile instead of O(B^2)), and run Union-Find across shared tile borders (total = sum(tile_counts) - border_merges).
def count_regions_streaming(rows):
    """Stream an arbitrarily tall matrix row by row using O(n) memory."""
    parent = {}

    def find(label):
        while parent[label] != label:
            parent[label] = parent[parent[label]]
            label = parent[label]
        return label

    regions = 0
    next_label = 0
    prev_row = None

    for row in rows:
        cur_row = [None] * len(row)
        for col, cell in enumerate(row):
            if cell != 1:
                continue
            if col > 0 and cur_row[col - 1] is not None:
                cur_row[col] = cur_row[col - 1]
            else:
                cur_row[col] = next_label
                parent[next_label] = next_label
                next_label += 1
                regions += 1
            if prev_row is not None and prev_row[col] is not None:
                root_a = find(cur_row[col])
                root_b = find(prev_row[col])
                if root_a != root_b:
                    parent[root_a] = root_b
                    regions -= 1

        # Compact active labels to their current roots so forgotten rows take zero RAM.
        for col, label in enumerate(cur_row):
            if label is not None:
                cur_row[col] = find(label)
        parent = {label: label for label in cur_row if label is not None}
        prev_row = cur_row

    return regions

Follow-up questions

Similar questions

More Illumio interview questions

All 4 Illumio questions →