Command Palette

Search for a command to run...

← All patterns

Pattern · Graphs

Graph DFS and Flood Fill

Go as deep as possible from a node, marking visited cells or nodes, to find connected regions.

Time O(V + E) or O(rows × cols) · Space O(V) recursion depth

Taught in Module 22: Depth-First Search

Think of it like this

Exploring a cave system with a ball of string: follow one tunnel to its end before coming back to try the next.

Clues that point here

  • → Count islands or connected components
  • → Flood fill, surrounded regions
  • → Can you reach X from Y?
  • → Clone a graph

Not this pattern when

  • ✕ You need the shortest path (BFS)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Graph DFS and Flood Fill · template
void dfs(char[][] grid, int r, int c) {
    if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) return;
    if (grid[r][c] != '1') return;       // water or already visited
    grid[r][c] = '#';                    // mark visited
    dfs(grid, r + 1, c); dfs(grid, r - 1, c);
    dfs(grid, r, c + 1); dfs(grid, r, c - 1);
}

Common versions

  • Number of islands
  • Max area of island
  • Pacific Atlantic water flow
  • Clone graph
  • Surrounded regions

Practice problems with this pattern

Related patterns