AlgoViz

Matrix DFS

medium 20 min

A 2D grid is a graph in disguise: every cell is a node and its up, down, left and right neighbours are its edges.

Video lesson · Chapter 1 of 6

Where can the water reach?

0:00 / 5:00

Matrix depth-first search — The five-pixel octopus

1:06Reel

Read caption

Tess recolors an octopus made of five connected pixels. Watch the brush backtrack at a dead end and leave a diagonal mark untouched. Mark it. Go deep. Back up at a dead end.

How it works

Step through the idea, or press Play.

Step 1 of 3

Read the grid as a graph. Each cell is a node; its four neighbours are edges, found with a direction array and a bounds check

Understand it

Start here

A grid is a graph in disguise

A map of land and water, a picture of pixels, a maze of walls: all are 2D grids. Treat each cell as a node and connect it to the cells directly above, below, left and right, and you have a graph. Nobody builds an adjacency list: the neighbours of (r,c)(r, c) are computed on the fly. That is why a grid is called an implicit graph.

How big is that graph?

V=R⋅C,E=R(C−1)+C(R−1)  <  2RCV = R \cdot C, \qquad E = R(C-1) + C(R-1) \;<\; 2RC
An R×CR \times C grid has one node per cell. Each row has C−1C - 1 horizontal edges and each column R−1R - 1 vertical ones, so every cell has at most 4 edges and the graph is sparse: E=O(V)E = O(V).
  • Islands

    Count groups of connected land, find the largest one, measure a perimeter.

  • Flood fill

    The paint bucket tool: recolour every connected cell of the same colour.

  • Paths

    Can you get from S to E through open cells? Solve a maze, check reachability.

Neighbours

Four directions and the bounds check

Moving up means row −1-1, down row +1+1, left column −1-1, right column +1+1. Store those four offsets in a list and loop over it, so you never write four nearly identical lines. Every neighbour must then pass the bounds check 0≤r<R0 \le r < R and 0≤c<C0 \le c < C before you read the grid.

Python
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]   # up, down, left, rightdef neighbours(grid, r, c):    rows, cols = len(grid), len(grid[0])    for dr, dc in DIRS:        nr, nc = r + dr, c + dc        if 0 <= nr < rows and 0 <= nc < cols:   # bounds check first            yield nr, ncgrid = [[1, 1, 0],        [1, 0, 0],        [0, 0, 1]]print(list(neighbours(grid, 0, 0)))   # [(1, 0), (0, 1)]: a corner has 2print(list(neighbours(grid, 1, 1)))   # [(0, 1), (2, 1), (1, 0), (1, 2)]: the centre has 4
The direction array and a neighbour helper. Rows are len(grid), columns are len(grid[0]).
Edit and run it in your browser
MovementOffsetsNeighboursUsed for
4-directional(-1,0) (1,0) (0,-1) (0,1)up to 4Islands, flood fill, mazes: the default
8-directionalthe 4 above plus (-1,-1) (-1,1) (1,-1) (1,1)up to 8When corners touch: Minesweeper, some image regions
Unless a problem says diagonals connect, use 4 directions. Land that meets only at a corner is two islands.

The template

Bounds, Valid, Mark, Recurse

One call of dfs(r, c)

B, V, M, R. Two cheap checks reject a cell; anything that passes is marked before a single recursive call is made.
Python
def dfs(grid, r, c, visited):    rows, cols = len(grid), len(grid[0])    if r < 0 or r >= rows or c < 0 or c >= cols:   # B: bounds        return    if (r, c) in visited or grid[r][c] == 0:       # V: valid?        return    visited.add((r, c))                             # M: mark    for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:        dfs(grid, r + dr, c + dc, visited)          # R: recursegrid = [[1, 1, 0],        [1, 0, 0],        [0, 0, 1]]seen = set()dfs(grid, 0, 0, seen)print(sorted(seen))   # [(0, 0), (0, 1), (1, 0)]: (2, 2) only touches at a corner
The template every grid DFS is built from. Change the valid check and what you do after marking; keep the rest.
Edit and run it in your browser
The call stack on that 3×3 grid
  1. 1dfs(0,0)mark; up is out of bounds
  2. 2dfs(1,0)down: mark; all 4 neighbours rejected
  3. 3back in (0,0)left is out of bounds
  4. 4dfs(0,1)right: mark; all 4 neighbours rejected
  5. 5return3 cells visited, deepest stack 2

Every rejected call costs one check and returns at once. Only accepted cells add a frame that stays open.

Visited

Marking visited: in place or with a set

You need some record of which cells are done. Either keep a separate visited structure, or overwrite the cell itself: sink land 1 to 0, paint a pixel the new colour, or write a marker such as "#".

In place

  • No extra set: saves O(R⋅C)O(R \cdot C) memory.
  • One check does double duty: a sunk cell looks like water.
  • Destroys the input: copy first if the caller needs it.
  • Natural for flood fill, where painting is the job.

Visited set or matrix

  • Input stays untouched: safer in shared code.
  • A [[False] * C for _ in range(R)] matrix is faster than a set of tuples.
  • Costs O(R⋅C)O(R \cdot C) extra memory.
  • Needed when the grid is read-only or reused.
ProblemUsual markWhy
Number of islandsset grid[r][c] = "0" or a visited matrixA sunk cell can never start another island
Flood fillthe new colourA painted cell no longer matches the original colour
Max area of islandset to 0The DFS return value is the count; no set needed
Word Search (a backtracking cousin)mark, then unmark on returnA cell may be reused by a different path

Two ways

Recursive and iterative flood fill

Recursion keeps the cells waiting to be finished on the call stack. You can keep them on your own list instead: push the start, then repeatedly pop the newest cell, skip it if visited, mark it and push its valid neighbours. Popping the newest is last in, first out, a stack, so the walk is still depth-first.

Python
def dfs_iterative(grid, sr, sc):    rows, cols = len(grid), len(grid[0])    visited = set()    stack = [(sr, sc)]    while stack:        r, c = stack.pop()                  # newest cell first: depth-first        if (r, c) in visited:            continue                        # was pushed twice: skip the copy        visited.add((r, c))        for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:            nr, nc = r + dr, c + dc            if 0 <= nr < rows and 0 <= nc < cols:                if (nr, nc) not in visited and grid[nr][nc] == 1:                    stack.append((nr, nc))    return visitedgrid = [[1, 1, 0],        [1, 1, 0],        [0, 0, 0]]print(len(dfs_iterative(grid, 0, 0)))   # 4
Iterative DFS. Swap stack.pop() for a deque's popleft() and the same loop becomes BFS.
Edit and run it in your browser

The iterative loop

A cell can sit on the stack twice before it is popped. The visited check on pop throws the copy away; marking on push instead avoids the copies altogether.

Iterative

  • No recursion limit: safe on a 1000 × 1000 grid.
  • Change one line to get BFS.
  • Slightly more code.

Recursive

  • Shortest and clearest: start here in interviews.
  • Python stops at about 1,000 nested calls.
  • Easy to return values up (area, True or False).

Pattern 1

Number of islands: count the DFS starts

Scan every cell in reading order. When the scan meets land that is not yet visited, it must be a new island, because every earlier island was visited completely by its own DFS. Count it, then run DFS to mark the whole island so the scan skips the rest of it.

Scan plus DFS

On the 4×5 grid 11000 / 11000 / 00100 / 00011 the scan starts DFS at (0,0), (2,2) and (3,3): three islands.
Python
def num_islands(grid):    rows, cols = len(grid), len(grid[0])    def sink(r, c):        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":            return        grid[r][c] = "0"                    # mark by sinking        sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1)    islands = 0    for r in range(rows):        for c in range(cols):            if grid[r][c] == "1":                sink(r, c)                islands += 1                # once per DFS start    return islandsgrid = [list("11000"), list("11000"), list("00100"), list("00011")]print(num_islands(grid))   # 3
Number of islands with in-place sinking. Each cell is scanned once and sunk at most once.
Edit and run it in your browser

Pattern 2

Max area of island: return a count

Instead of returning nothing, let the DFS return how many cells it visited. A rejected cell (outside, water, already sunk) is worth 0; an accepted cell is worth 1 plus whatever its four neighbours bring back. The scan keeps the largest answer.

The area recurrence

area(r,c)={0outside, water or visited1+∑(dr, dc)area(r+dr, c+dc)otherwise\text{area}(r, c) = \begin{cases} 0 & \text{outside, water or visited} \\ 1 + \displaystyle\sum_{(dr,\,dc)} \text{area}(r + dr,\ c + dc) & \text{otherwise} \end{cases}
The sum runs over the four directions. Because each cell is sunk before the recursive calls, it is counted exactly once, so the total is the island's size.
Python
def max_area(grid):    rows, cols = len(grid), len(grid[0])    def area(r, c):        if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:            return 0        grid[r][c] = 0                      # sink before recursing        return (1 + area(r - 1, c) + area(r + 1, c)                  + area(r, c - 1) + area(r, c + 1))    best = 0    for r in range(rows):        for c in range(cols):            if grid[r][c] == 1:                best = max(best, area(r, c))    return bestgrid = [[0, 1, 1, 0, 0],        [0, 1, 0, 0, 1],        [1, 0, 0, 1, 1],        [1, 1, 0, 0, 1]]print(max_area(grid))   # 4: islands of 3, 4 and 3
Max area of island, values returned up the call stack like a postorder tree DFS.
Edit and run it in your browser

Pattern 3

Flood fill and path existence

Flood fill recolours every cell connected to (sr,sc)(s_r, s_c) that has its original colour. The new colour is the visited mark, so no set is needed, with one trap: if the new colour equals the original, painted cells still match and DFS never ends. Path existence asks whether the end cell is reachable at all; DFS returns True on reaching it, and or stops the remaining directions from running.

dfs(r, c) for path existence

The first True travels straight back up through every waiting call. A False answer needs the whole reachable region explored.
Python
def flood_fill(image, sr, sc, color):    original = image[sr][sc]    if original == color:        return image                        # guard against an endless loop    def paint(r, c):        if 0 <= r < len(image) and 0 <= c < len(image[0]) and image[r][c] == original:            image[r][c] = color            paint(r - 1, c); paint(r + 1, c); paint(r, c - 1); paint(r, c + 1)    paint(sr, sc)    return imagedef has_path(grid, start, end):           # 0 = open, 1 = wall    rows, cols, seen = len(grid), len(grid[0]), set()    def dfs(r, c):        if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] == 1 or (r, c) in seen:            return False        if (r, c) == end:            return True        seen.add((r, c))        return dfs(r - 1, c) or dfs(r + 1, c) or dfs(r, c - 1) or dfs(r, c + 1)    return dfs(*start)print(flood_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2))   # [[2, 2, 2], [2, 2, 0], [2, 0, 1]]maze = [[0, 0, 1, 0, 0],        [1, 0, 1, 0, 1],        [0, 0, 0, 0, 1],        [0, 1, 1, 0, 0]]print(has_path(maze, (0, 0), (3, 4)))   # Truemaze[3][3] = 1print(has_path(maze, (0, 0), (3, 4)))   # False
Flood fill and path existence side by side.
Edit and run it in your browser

Complexity

O(R·C) time and space

Every cell is marked at most once. Each marked cell makes 4 calls, and every rejected call costs O(1)O(1). The scan loop adds one look at each cell.

Time

T(R,C)=RC⏟scan+RC⏟marks+4RC⏟neighbour calls=6RC=O(R⋅C)T(R, C) = \underbrace{R C}_{\text{scan}} + \underbrace{R C}_{\text{marks}} + \underbrace{4 R C}_{\text{neighbour calls}} = 6RC = O(R \cdot C)
An upper bound: the marks and the calls only happen for land cells. With 8 directions the constant becomes 10, still O(R⋅C)O(R \cdot C), which is O(V+E)O(V + E) for the implicit graph.

Space, including recursion depth

S(R,C)=O(RC)⏟visited+O(d)⏟call stack,d≤R⋅CS(R, C) = \underbrace{O(R C)}_{\text{visited}} + \underbrace{O(d)}_{\text{call stack}}, \qquad d \le R \cdot C
The depth dd is the longest chain of open calls. A snake-shaped island (or the flood scene in the visualizer, 19 calls deep for 23 cells) pushes dd towards R⋅CR \cdot C. Sinking in place drops the first term but never the second.
ApproachTimeExtra space (worst case)
Recursive DFS + visited setO(R⋅C)O(R \cdot C)O(R⋅C)O(R \cdot C) set + O(R⋅C)O(R \cdot C) stack
Recursive DFS, sink in placeO(R⋅C)O(R \cdot C)O(R⋅C)O(R \cdot C) call stack
Iterative DFS, explicit stackO(R⋅C)O(R \cdot C)O(R⋅C)O(R \cdot C) list, no recursion limit
BFS with a queueO(R⋅C)O(R \cdot C)O(R⋅C)O(R \cdot C) bound; the frontier is often far smaller
All four do the same total work. They differ in where the waiting cells live and how deep the call stack can go.

Python

The recursion limit

CPython allows about 1,000 nested calls by default. A 40 × 40 grid of solid land can already need more than that, and the result is RecursionError: maximum recursion depth exceeded. sys.setrecursionlimit raises the ceiling, but each Python frame also uses the C stack, so a large enough limit crashes the whole interpreter instead.

Python
import sysdef sink_recursive(grid, r, c):    if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1:        grid[r][c] = 0        for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:            sink_recursive(grid, r + dr, c + dc)def sink_iterative(grid, r, c):    stack = [(r, c)]    while stack:        r, c = stack.pop()        if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 1:            grid[r][c] = 0            stack.extend([(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)])print("limit:", sys.getrecursionlimit())snake = [[1] * 3000]                       # one row of 3,000 land cellstry:    sink_recursive([row[:] for row in snake], 0, 0)    print("recursive: ok")except RecursionError:    print("recursive: RecursionError")sink_iterative(snake, 0, 0)print("iterative: ok, cells left =", sum(snake[0]))   # 0
Recursion fails on a long snake of land; the explicit stack does not care.
Edit and run it in your browser

DFS or BFS

When to reach for BFS instead

Pick the grid traversal

Both visit each cell once. BFS reaches cells in order of distance; DFS reaches them in whatever order the dive takes.

Matrix DFS

  • Recursion or a stack, goes deep first.
  • Counting islands, flood fill, areas, any path.
  • Less code: the recursion holds the state.
  • Does not find shortest paths.

Matrix BFS

  • A queue, spreads in rings.
  • Shortest path in an unweighted grid, rotting oranges, distance to nearest.
  • No recursion limit.
  • See Matrix BFS.

Recap

Key takeaways

Key points

  • A grid is an implicit graph: R·C nodes, edges to the up, down, left and right neighbours.
  • Neighbours come from a direction array; check 0 ≤ r < R and 0 ≤ c < C before indexing, because Python's negative indexes wrap.
  • Template: Bounds, Valid, Mark, Recurse. Mark before the recursive calls.
  • Mark visited with a set or matrix, or in place by sinking or painting the cell.
  • Number of islands = number of DFS starts in the scan. Max area: DFS returns 1 + its neighbours' areas.
  • Flood fill: the new colour is the mark; return early if it equals the original.
  • Path existence: DFS returns True at the end cell and or stops the search; it finds a path, not the shortest.
  • O(R·C) time and O(R·C) space, including a call stack up to R·C deep. Use an explicit stack in Python for big grids.

Sources