← All patterns
17 / 32
Graphs & Networks

Graph DFS

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

connected componentsislandsflood fillcycle in graphreachableregions
Practice

Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.

Ask yourself

  1. Explore a maze/grid/graph fully?
  2. Count components / islands / flood fill?
  3. Mark visited; recurse to neighbours.

Classic problem

Number of Islands (LeetCode 200) — count groups of connected "1" cells in a grid. Each unvisited land cell starts a DFS that floods its whole island.

Input: grid = [["1","1","0"],["0","1","0"],["1","0","1"]]

Output: 3 — top-left cluster, center cell, and bottom-right cell are three separate islands.

Watch it run

Common pitfalls

Forgetting visited → infinite recursion.

Stack overflow on deep graphs (use iterative).