Kodewick
Start learning →
Depth-first search (DFS)32 / 52

Depth-first search (DFS)

Lesson 32 of 52 · Part 6 · Graphs · about 17 minutes

Depth-first search (DFS) follows one path as far as it can, then backs up and tries another; the recursive version is shortest, but Python's call stack holds only about 1000 levels, so deep graphs raise RecursionError unless you keep your own stack in a list.

There is an old way through a maze: keep one hand on the wall, follow a path as far as it goes, and at a dead end back up to the last fork and take a way not tried yet. That is depth-first search (DFS). Like BFS, it finds every vertex that can be reached, and it is the tool for counting how many pieces a graph falls into, finding cycles and topological sorting. Written with recursion it takes five or six lines, but Python's call stack only holds about a thousand levels: a follow chain of a hundred thousand people in a social network, or a thousand-by-thousand map, and the recursive version raises RecursionError before it is halfway. This lesson writes both versions, shows why they visit in different orders, and when you have to switch to a stack of your own.

Down one path as far as it goes

The recursive version: visit u and mark it; then look at u's neighbours in order, and for one not yet seen, recurse into it straight away; only when that whole call has finished and returned, look at the next neighbour.

Recursive DFS from A: blue is still on the call stack (not finished), green has returned; neighbours are looked at in the order the lists store them
main.py
1graph = {2    "A": ["B", "C"],3    "B": ["A", "D"],4    "C": ["A", "D", "E"],5    "D": ["B", "C", "F"],6    "E": ["C", "F"],7    "F": ["D", "E"],8}9 10def dfs(graph, u, seen, order):11    seen.add(u)12    order.append(u)13    for v in graph[u]:14        if v not in seen:15            dfs(graph, v, seen, order)16 17order = []18dfs(graph, "A", set(), order)19print(order)20 21order = []22dfs(graph, "F", set(), order)23print(order)
Output
['A', 'B', 'D', 'C', 'E', 'F']
['F', 'D', 'B', 'A', 'C', 'E']

Compare with BFS in the last lesson: on the same graph, BFS gives A B C D E F (layer by layer), DFS gives A B D C E F (one path first, as deep as F). The time is the same O(n + e): each vertex entered once, each edge looked at once from each end.

Guess the outputA wrong guess is fine

The same graph as the BFS guess in the last lesson, now with recursive DFS. What does it print?

1graph = {1: [3, 2], 2: [4], 3: [4, 5], 4: [6], 5: [6], 6: []}2order = []3seen = set()4 5def dfs(u):6    seen.add(u)7    order.append(u)8    for v in graph[u]:9        if v not in seen:10            dfs(v)11 12dfs(1)13print(order)
Choose one

An undirected graph has the edges A–C, A–E, C–B, C–D, E–F, B–F, and neighbours are looked at in alphabetical order. In what order does DFS from A visit the vertices?

A stack of your own

Recursion runs on the call stack: dfs(A) calls dfs(B), and A's level waits underneath. Swap that stack for a list of your own and you have the explicit stack version:

  1. Push the start.
  2. While the stack is not empty: pop u; if u was seen, skip it; if not, visit and mark it, then push its neighbours that have not been seen.

Stack

The explicit stack from A: neighbours are pushed as B, then C, and C, pushed last, pops first, so the walk goes C's way first; the same vertex can sit on the stack twice
main.py
1graph = {2    "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],3    "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"],4}5 6def dfs_stack(graph, start):7    seen = set()8    stack = [start]9    order = []10    while stack:11        u = stack.pop()12        if u in seen:                    # the stack can hold repeats: skip them when popped13            continue14        seen.add(u)15        order.append(u)16        for v in graph[u]:17            if v not in seen:18                stack.append(v)19    return order20 21def dfs_stack_same(graph, start):22    seen = set()23    stack = [start]24    order = []25    while stack:26        u = stack.pop()27        if u in seen:28            continue29        seen.add(u)30        order.append(u)31        for v in reversed(graph[u]):     # push in reverse: the first neighbour ends on top32            if v not in seen:33                stack.append(v)34    return order35 36def dfs_rec(graph, start):37    seen, order = set(), []38    def go(u):39        seen.add(u)40        order.append(u)41        for v in graph[u]:42            if v not in seen:43                go(v)44    go(start)45    return order46 47print("recursive:     ", dfs_rec(graph, "A"))48print("explicit stack:", dfs_stack(graph, "A"))49print("pushed reversed:", dfs_stack_same(graph, "A"))
Output
recursive:      ['A', 'B', 'D', 'C', 'E', 'F']
explicit stack: ['A', 'C', 'E', 'F', 'D', 'B']
pushed reversed: ['A', 'B', 'D', 'C', 'E', 'F']

The orders differ because a stack is last in, first out: A's neighbours go in as B, then C, and C comes out first. Both are proper DFS and both find every reachable vertex; when a problem wants "the same order as the recursion", push the neighbours in reverse (reversed), so the first neighbour is on top and is the next one popped.

Here a vertex is marked when it is popped, the opposite of the BFS lesson. That is because DFS wants "the most recently found goes first": F found D later than B did, so the walk should carry on to D from F's side. Marking on pop means the stack can hold repeats, so look first when you pop: if u in seen: continue. When you only want "what can be reached" and the order does not matter, you can also mark on push as BFS does, and the stack never holds a repeat.

RecursiveExplicit stack
Writing itshortest, five or six linesa few more lines, repeats to handle
Visit orderneighbours in stored orderpushing in stored order reverses it; pushing reversed matches the recursion
Depth limitabout 1,000 levels of call stack (CPython's default)only memory: millions of levels are fine
When a vertex is "finished"when its call returns, built inhas to be tracked separately (needed for topological sort and cycles)
Guess the outputA wrong guess is fine

The same graph as the guess at the start of this lesson, now with an explicit stack: neighbours pushed in stored order, marked when popped. What does this print?

1graph = {1: [3, 2], 2: [4], 3: [4, 5], 4: [6], 5: [6], 6: []}2seen = set()3stack = [1]4order = []5while stack:6    u = stack.pop()7    if u in seen:8        continue9    seen.add(u)10    order.append(u)11    for v in graph[u]:12        if v not in seen:13            stack.append(v)14print(order)
Exercise 1

The same order as the recursion

Complete dfs_order(graph, start): with an explicit stack, return exactly the visit order of recursive DFS. Mark on pop and push the neighbours in reverse.

It should print
['A', 'B', 'D', 'C', 'E', 'F']
['E', 'C', 'A', 'B', 'D', 'F']
exercise1.py
1def dfs_order(graph, start):2    seen = set()3    stack = [start]4    order = []5    # pop u: skip it if seen; otherwise visit it, then push its unseen neighbours in reverse6    return order7 8graph = {9    "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"],10    "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"],11}12print(dfs_order(graph, "A"))13print(dfs_order(graph, "E"))
Output
Press Run or Ctrl+Enter

Connected components: how many pieces

In an undirected graph, vertices that can all reach each other form one piece, a connected component. To count them, start a DFS from each vertex not yet seen and give everything it reaches the same number; the number of DFS runs is the number of pieces.

8 vertices in 3 pieces: from 0, piece 1 gets labelled; 3 is the next unseen vertex and starts piece 2; 5 starts piece 3
main.py
1n = 82edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7), (5, 7)]3graph = [[] for _ in range(n)]4for u, v in edges:5    graph[u].append(v)6    graph[v].append(u)7 8comp = [0] * n                       # 0 = not seen yet; 1, 2, 3… = which piece9 10def dfs(u, k):11    comp[u] = k12    for v in graph[u]:13        if comp[v] == 0:14            dfs(v, k)15 16count = 017for u in range(n):18    if comp[u] == 0:19        count += 120        dfs(u, count)21print("pieces:", count)22print("piece of each vertex:", comp)23print("0 and 2 connected:", comp[0] == comp[2], " 2 and 3:", comp[2] == comp[3])
Output
pieces: 3
piece of each vertex: [1, 1, 1, 2, 2, 3, 3, 3]
0 and 2 connected: True  2 and 3: False

The one list comp does two jobs: comp[u] == 0 means "not seen", and a non-zero value says which piece u is in. After that, "are u and v connected" is just comp[u] == comp[v], O(1).

Choose one

7 vertices (0 to 6), with the edges 0–4, 1–5, 4–2, 5–6. How many connected components are there?

Exercise 2

Count connected components

Complete count_components(n, edges): the vertices are 0 to n − 1 and the edges are undirected; return how many pieces the graph falls into. Write the DFS with an explicit stack (no recursion).

It should print
2
1
4
exercise2.py
1def count_components(n, edges):2    graph = [[] for _ in range(n)]3    for u, v in edges:4        graph[u].append(v)5        graph[v].append(u)6    seen = [False] * n7    count = 08    # for each unseen vertex: count goes up by one, and a stack marks everything reachable from it9    return count10 11print(count_components(5, [(0, 1), (1, 2), (3, 4)]))12print(count_components(5, [(0, 1), (1, 2), (2, 3), (3, 4)]))13print(count_components(4, []))
Output
Press Run or Ctrl+Enter

Too deep: RecursionError

The examples in this lesson's earlier steps are only a few levels deep. But the depth of a DFS is the longest path it walks: on a path of 10,000 vertices 0 – 1 – 2 – … – 9999, the recursive version stacks 10,000 calls one inside another.

main.py
1n = 100002graph = [[i - 1, i + 1] for i in range(n)]     # one long path: 0 - 1 - 2 - … - 99993graph[0] = [1]4graph[n - 1] = [n - 2]5 6def dfs(u, seen):7    seen.add(u)8    for v in graph[u]:9        if v not in seen:10            dfs(v, seen)11 12try:13    dfs(0, set())14    print("the recursive version finished")15except RecursionError:16    print("recursive version: RecursionError")17 18def dfs_stack(start):19    seen = set()20    stack = [start]21    while stack:22        u = stack.pop()23        if u in seen:24            continue25        seen.add(u)26        for v in graph[u]:27            if v not in seen:28                stack.append(v)29    return len(seen)30 31print("the explicit stack reached", dfs_stack(0), "vertices")
Output
recursive version: RecursionError
the explicit stack reached 10000 vertices

The recursive version stops at around a thousand levels; a list holding 10,000 items is no trouble at all for the explicit stack. When the size of the graph is not under your control (user data, grid maps, a problem saying n ≤ 10⁵), write DFS with an explicit stack.

A "fix" often seen online is sys.setrecursionlimit(10**6). It only loosens Python's own check; the C stack underneath gets no bigger, and when the recursion really goes deep the program crashes outright, without even an error message. Don't rely on it.

In interviews: "BFS versus DFS": BFS uses a queue and walks by layers, so it finds the fewest steps; DFS uses a stack (recursion is the call stack) and goes down one path as far as it can, which suits finding all paths, components, cycles and topological orders; both are O(n + e). Add "Python's recursion depth is limited, so deep graphs need an explicit stack", and you have hit the point.

Choose one

The graph is one long chain 0–1–2–…–(n − 1), and recursive DFS starts from 0. At its deepest, how many dfs calls are on the call stack at once?

Choose one

The problem says n ≤ 10⁵, and the graph may be one long chain. What is the safest way to write the DFS?

How you write it at work

The standard library has no ready-made DFS; what you write by hand are the two versions from this lesson, recursive and with a stack. In practice:

  • A small graph whose depth is known (a tree a few dozen levels tall): recursion is the clearest.
  • Depth unknown: an explicit stack, stack = [start], stack.pop(), stack.append(v); a list's end is O(1) for both.
  • Only "what can be reached": BFS or DFS, whichever is easier to write; the fewest steps: only BFS.
  • In a recursive function, pass seen and order as arguments or keep them in an enclosing function as a closure, not in globals: call the function a second time and the old seen is still there.
main.py
1def reachable(graph, start):2    seen = {start}3    stack = [start]4    while stack:5        u = stack.pop()6        for v in graph.get(u, []):       # a vertex with no out-edges need not be in the dict7            if v not in seen:8                seen.add(v)              # only "what can be reached": mark on push9                stack.append(v)10    return sorted(seen)11 12follows = {"a": ["b"], "b": ["c", "d"], "d": ["a"], "e": ["a"]}13print(reachable(follows, "a"))14print(reachable(follows, "e"))15print(reachable(follows, "c"))
Output
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['c']
Guess the outputA wrong guess is fine

seen lives outside the function: it is global. The graph is in two pieces, 1–2 and 3–4. What does this print?

1seen = set()2 3def dfs(graph, u):4    seen.add(u)5    for v in graph[u]:6        if v not in seen:7            dfs(graph, v)8    return len(seen)9 10g = {1: [2], 2: [1], 3: [4], 4: [3]}11print(dfs(g, 1), dfs(g, 3))

Summary

Take-away

DFS: down one path, then back

  • Recursive: visit, mark, and recurse into an unseen neighbour at once; O(n + e)
  • Explicit stack: mark on pop, skip what was seen; push neighbours reversed to match the recursion
  • Connected components: one DFS per unseen vertex; the number of runs is the number of pieces
  • The depth is the longest path: 10,000 levels of recursion raise RecursionError, so use an explicit stack
  • setrecursionlimit hides the problem: too deep and the program crashes
1stack = [start]2while stack:3    u = stack.pop()4    if u in seen: continue5    seen.add(u)6    stack.extend(v for v in reversed(graph[u]) if v not in seen)