Kodewick
Start learning →
Depth-first search30 / 50

Depth-first search (DFS)

Lesson 30 of 50 · Part 6 · Graphs · about 17 minutes

Depth-first search (DFS) follows one path as far as it goes, then backs up to the last fork; written recursively it marks seen[u] = 1 and calls dfs(v) on each unseen neighbour, and it counts connected components and finds cycles.

There's an old way through a maze: keep one hand on the wall and follow one path to its end; at a dead end, go back to the last fork and take a way you haven't tried. That's depth-first search (DFS). It doesn't care about near or far; it cares about "can I get there?", "how many separate pieces are there?", "is there a loop that comes back round?". Written recursively, the heart of it is four or five lines.

One path to the end

1void dfs(int u) {2    seen[u] = 1;3    for (each neighbour v)4        if (!seen[v]) dfs(v);5}

dfs(u) marks u, then goes down into the first unseen neighbour at once, and only when that's completely finished comes back for the next neighbour. "Going back to the fork" needs no code: returning from a function lands you back in the call that made it, and the call stack remembers which neighbour each level had got to.

call stack

DFS from 0 on the same graph as last lesson (neighbours looked at in increasing order). The row below is the call stack, with the running dfs on the right; thick lines are the edges it walked down; blue is still on the call stack, not finished; green has finished and returned

BFS visited both of 0's neighbours, 2 and 4, first; DFS visits 2 and dives straight down, and 4's turn comes last. Both visit each vertex once and look at each edge twice (once from each end), so DFS is O(n + e) too (O(n²) with a matrix). The thick lines make a tree (the DFS spanning tree), which isn't last lesson's BFS tree: a DFS tree is tall and thin, a BFS tree short and wide.

main.c
1#include <stdio.h>2 3#define N 64 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9void dfs(int u, int depth) {10    seen[u] = 1;11    printf("%*sin  %d\n", depth * 2, "", u);    // indent = depth of recursion12    for (int v = 0; v < N; v++)13        if (a[u][v] && !seen[v])14            dfs(v, depth + 1);15    printf("%*sout %d\n", depth * 2, "", u);16}17 18int main(void) {19    add(0, 2); add(0, 4); add(2, 1); add(2, 3);20    add(4, 3); add(1, 5); add(3, 5);21    dfs(0, 0);22    return 0;23}
Output
in  0
  in  2
    in  1
      in  5
        in  3
          in  4
          out 4
        out 3
      out 5
    out 1
  out 2
out 0

The indent is the depth of the call stack: 6 levels at its deepest. A graph that's one long chain needs n levels of recursion for n vertices; with n at a million the default few-MB stack runs out (a stack overflow). That's when you want the non-recursive version from the section "Without recursion: your own stack".

Guess the outputA wrong guess is fine

DFS from 0. What does it print?

1#include <stdio.h>2 3#define N 54 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9void dfs(int u) {10    seen[u] = 1;11    printf("%d ", u);12    for (int v = 0; v < N; v++)13        if (a[u][v] && !seen[v])14            dfs(v);15}16 17int main(void) {18    add(0, 1); add(0, 2); add(1, 3); add(2, 3); add(0, 4);19    dfs(0);20    printf("\n");21    return 0;22}
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?

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?

Counting connected components

One call dfs(s) reaches exactly the vertices connected to s: a connected component (a piece). So to count the pieces: look at 0 to n − 1 in turn, and each vertex not yet seen starts a new piece; dfs from it once to mark the whole piece.

8 vertices in three pieces that don't touch. The number on a vertex is which piece it's in

BFS can count pieces just as well; DFS is simply shorter to write.

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 1

Count the pieces

Finish the loop in main: each time it meets an unseen vertex, add 1 to the count and run dfs from it.

It should print
4
exercise1.c
1#include <stdio.h>2 3#define N 94 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9void dfs(int u) {10    seen[u] = 1;11    for (int v = 0; v < N; v++)12        if (a[u][v] && !seen[v])13            dfs(v);14}15 16int main(void) {17    add(0, 3); add(3, 6); add(1, 4); add(2, 5); add(5, 8); add(8, 2);18    int count = 0;19    // i from 0 to N - 1: if unseen, count++ and dfs(i)20    printf("%d\n", count);21    return 0;22}
Output
Press Run or Ctrl+Enter

Is there a cycle?

In an undirected graph, when DFS at u finds a neighbour v already seen, there are two possibilities: v is the parent that just brought us to u (we've just walked that edge), or v is some other vertex seen earlier, which means we've gone round and come back: a cycle. So pass the parent down with the recursion:

main.c
1#include <stdio.h>2 3#define N 64 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9int dfs(int u, int parent) {        // returns 1 if it finds a cycle10    seen[u] = 1;11    for (int v = 0; v < N; v++) {12        if (!a[u][v]) continue;13        if (!seen[v]) {14            if (dfs(v, u)) return 1;15        } else if (v != parent) {   // seen, and not the parent: we came round16            printf("edge %d-%d leads back to a seen vertex, ", u, v);17            return 1;18        }19    }20    return 0;21}22 23int main(void) {24    add(0, 2); add(0, 4); add(2, 1); add(2, 3);25    add(4, 3); add(1, 5); add(3, 5);26    printf("%s\n", dfs(0, -1) ? "cycle" : "no cycle");27 28    for (int i = 0; i < N; i++)              // another graph: a tree29        for (int j = 0; j < N; j++)30            a[i][j] = 0;31    for (int i = 0; i < N; i++) seen[i] = 0;32    add(0, 1); add(0, 2); add(1, 3); add(1, 4); add(2, 5);33    printf("%s\n", dfs(0, -1) ? "cycle" : "no cycle");34    return 0;35}
Output
edge 3-2 leads back to a seen vertex, cycle
no cycle

Looking for a cycle from 0: down 0 → 2 → 1 → 5 → 3, then 3 sees 2, already seen and not its parent: a cycle. Blue is still on the call stack

The first graph goes down 0 → 2 → 1 → 5 → 3, and at 3 the first neighbour it looks at is 2: seen, and not 3's parent 5, so the cycle 2-1-5-3-2 is found and the calls return straight back up; 4 is never even visited. The second graph has 6 vertices and 5 edges and is a tree, with no cycle. (A connected graph on n vertices with exactly n − 1 edges is a tree; one more edge always makes a cycle.)

A directed graph can't be checked this way: there, "seen" has to be split into "still in the recursion" and "finished", and the next lesson, topological sort, gives an easier way.

Choose allPick all that apply

Which undirected graphs have a cycle? (You can pick more than one.)

Choose one

Change else if (v != parent) to plain else (seen means a cycle). What do you get when you check a tree?

Without recursion: your own stack

Recursion uses the system's call stack; with a stack of your own there's no overflow to fear. Here's how: the stack holds "vertices to go to"; pop one, and as it's popped, if it hasn't been seen, visit it and push its unseen neighbours. To get the same order as the recursion (smaller numbers first), push the neighbours from largest to smallest, so the smallest is on top.

stack (top on the right)

The same graph, DFS with your own stack: mark when popped, push neighbours largest first. A vertex can be in the stack twice; if it's seen when popped, skip it

If you mark when pushing, as BFS does, there are no repeats on the stack, but the order is no longer true DFS (2's neighbour 3 gets marked early, so it can't be reached from 5 any more). For the "one path to the end" order, mark when popping.

DFSBFS
Usesrecursion (the call stack) or a stacka queue
Movesone path to the end, then backout level by level
TimeO(n + e); matrix O(n²)O(n + e); matrix O(n²)
Good atcomponents, cycles, topological sort, backtrackingshortest paths unweighted, levels
Spanning treetall and thinshort and wide

In exams: as with BFS, "write the DFS order from v": unique for an adjacency matrix, chain order for an adjacency list. Also common: "how many times must DFS be called to visit all of an undirected graph with n vertices?" = the number of connected components; "the space complexity of recursive DFS" = O(n), n levels of recursion at worst.

Guess the outputA wrong guess is fine

Just one difference from this section's version: neighbours are pushed smallest first. Starting from 0, what does it print?

1#include <stdio.h>2 3#define N 44 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9int main(void) {10    add(0, 1); add(0, 2); add(1, 3); add(2, 3);11    int st[N * N], top = 0;12    st[top++] = 0;13    while (top > 0) {14        int u = st[--top];15        if (seen[u]) continue;16        seen[u] = 1;17        printf("%d ", u);18        for (int v = 0; v < N; v++)19            if (a[u][v] && !seen[v])20                st[top++] = v;21    }22    printf("\n");23    return 0;24}
Exercise 2

DFS with a stack

Finish the while loop: pop the top, u; skip it if it's seen; otherwise mark it, print it, and push its unseen neighbours from largest to smallest. The order printed should be the same as recursive DFS.

It should print
0 1 3 2 5 4
exercise2.c
1#include <stdio.h>2 3#define N 64 5int a[N][N], seen[N];6 7void add(int u, int v) { a[u][v] = a[v][u] = 1; }8 9int main(void) {10    add(0, 1); add(0, 2); add(1, 3); add(2, 3); add(3, 4); add(2, 5);11    int st[N * N], top = 0;12    st[top++] = 0;13    while (top > 0) {14        int u = st[--top];15        // if seen, continue; otherwise mark and print u, then v from N - 1 down to 0: push unseen neighbours16    }17    printf("\n");18    return 0;19}
Output
Press Run or Ctrl+Enter

Summary

Take-away

DFS: one path to the end, then back

  • Recursion: mark u, and dfs into each unseen neighbour at once
  • Counting pieces: go through in turn; each unseen vertex starts a new piece
  • Cycle in an undirected graph: a seen neighbour that isn't the parent
  • Without recursion: your own stack, mark on pop, push neighbours largest first
1void dfs(int u) {2    seen[u] = 1;3    for (int v = 0; v < N; v++)4        if (a[u][v] && !seen[v]) dfs(v);5}