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 to its end, then backs up to the last fork to try another; recursion makes it a few lines, since the call stack remembers the way back, and it counts connected components and finds cycles.

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

Follow 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 immediately recurses into the first unseen neighbour, and only after everything down there is done does it come back to look at the next neighbour. You never write "back up to the fork": returning from the function takes you back to the call that made it, and the call stack remembers which neighbour each call had got to.

call stack

DFS from 0 on the last lesson's graph (neighbours looked at in increasing order). The row below is the call stack, the dfs running now on the right; thick lines are edges walked along; blue means still on the call stack, unfinished, green means finished and returned

BFS visits both of 0's neighbours, 2 and 4, first; DFS visits 2 and dives straight down, and 4 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 form a tree (the DFS spanning tree), and it differs from the last lesson's BFS tree: the DFS tree is tall and thin, the BFS tree short and wide.

main.cpp
1#include <iostream>2#include <string>3using namespace std;4 5const int N = 6;6 7int a[N][N], seen[N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11void dfs(int u, int depth) {12    seen[u] = 1;13    cout << string(depth * 2, ' ') << "enter " << u << '\n';   // indent = recursion depth14    for (int v = 0; v < N; v++)15        if (a[u][v] && !seen[v])16            dfs(v, depth + 1);17    cout << string(depth * 2, ' ') << "leave " << u << '\n';18}19 20int main() {21    add(0, 2); add(0, 4); add(2, 1); add(2, 3);22    add(4, 3); add(1, 5); add(3, 5);23    dfs(0, 0);24    return 0;25}
Output
enter 0
  enter 2
    enter 1
      enter 5
        enter 3
          enter 4
          leave 4
        leave 3
      leave 5
    leave 1
  leave 2
leave 0

The indent is the depth of the call stack: 6 levels at its deepest. A graph shaped like one long chain needs n levels of recursion for n vertices; at hundreds of thousands or millions, g++'s default 8 MB stack can run out (a stack overflow) and the program crashes. That's when you switch to the version from the step «Without recursion: your own stack».

Guess the outputA wrong guess is fine

DFS from 0: what does it print?

1#include <iostream>2using namespace std;3 4const int N = 5;5 6int a[N][N], seen[N];7 8void add(int u, int v) { a[u][v] = a[v][u] = 1; }9 10void dfs(int u) {11    seen[u] = 1;12    cout << u << ' ';13    for (int v = 0; v < N; v++)14        if (a[u][v] && !seen[v])15            dfs(v);16}17 18int main() {19    add(0, 1); add(0, 2); add(1, 3); add(2, 3); add(0, 4);20    dfs(0);21    cout << '\n';22    return 0;23}
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 dfs(s) reaches exactly the vertices connected to s, which together are a connected component (a piece). So to count the pieces of a graph: go through 0 to n − 1, and each vertex not seen yet 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 belongs to

BFS counts pieces just as well; DFS is just shorter to write. The "With the STL" section counts this same graph.

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

Fill in the loop in main: each time you meet a vertex not seen yet, add 1 to the count and run dfs from it.

It should print
4
exercise1.cpp
1#include <iostream>2using namespace std;3 4const int N = 9;5 6int a[N][N], seen[N];7 8void add(int u, int v) { a[u][v] = a[v][u] = 1; }9 10void dfs(int u) {11    seen[u] = 1;12    for (int v = 0; v < N; v++)13        if (a[u][v] && !seen[v])14            dfs(v);15}16 17int main() {18    add(0, 3); add(3, 6); add(1, 4); add(2, 5); add(5, 8); add(8, 2);19    int count = 0;20    // i from 0 to N - 1: if not seen, count++ and dfs(i)21    cout << count << '\n';22    return 0;23}
Output
Press Run or Ctrl+Enter

Is there a cycle?

In an undirected graph, when DFS at u looks at a neighbour v that is already seen, there are two cases: v is the parent that brought us to u (we just came along 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 the recursion:

main.cpp
1#include <iostream>2using namespace std;3 4const int N = 6;5 6int a[N][N], seen[N];7 8void add(int u, int v) { a[u][v] = a[v][u] = 1; }9 10bool dfs(int u, int parent) {       // true when a cycle is found11    seen[u] = 1;12    for (int v = 0; v < N; v++) {13        if (!a[u][v]) continue;14        if (!seen[v]) {15            if (dfs(v, u)) return true;16        } else if (v != parent) {   // seen, and not the parent: we came round17            cout << "edge " << u << "-" << v << " leads back to a seen vertex, ";18            return true;19        }20    }21    return false;22}23 24int main() {25    add(0, 2); add(0, 4); add(2, 1); add(2, 3);26    add(4, 3); add(1, 5); add(3, 5);27    cout << (dfs(0, -1) ? "cycle" : "no cycle") << '\n';28 29    for (int i = 0; i < N; i++) {            // another graph: a tree30        seen[i] = 0;31        for (int j = 0; j < N; j++)32            a[i][j] = 0;33    }34    add(0, 1); add(0, 2); add(1, 3); add(1, 4); add(2, 5);35    cout << (dfs(0, -1) ? "cycle" : "no cycle") << '\n';36    return 0;37}
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 looked at is 2: seen, and not 3's parent 5, so the cycle 2-1-5-3-2 is found and true goes straight back up through every level; 4 is never even visited. The second graph has 6 vertices and 5 edges, a tree, so no cycle. (A connected graph on n vertices is a tree when it has exactly n − 1 edges; one more and it must have a cycle.)

That doesn't work for directed graphs: there you need two kinds of seen, "still being recursed" and "finished". The next lesson, topological sort, has a simpler 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; use your own stack<int> and stack overflow stops being a worry, since its elements live on the heap and millions fit. The stack holds "vertices to go to"; pop one, and when it's popped, if it isn't seen yet, visit it and push its unseen neighbours. To get the same order as the recursion (lowest number first), push the neighbours from high to low, so the lowest ends up on top.

stack (top on the right)

The same graph, DFS with a stack<int>: mark when popped, push neighbours from high to low. A vertex can be on the stack twice; when popped and already seen, it's skipped

Mark on push the way BFS does and the stack never holds duplicates, but the order is no longer true DFS (2's neighbour 3 gets marked early, so 5 can't go on to it). For the "follow one path to the end" order, mark when popped.

DFSBFS
Usesrecursion (the call stack) or a stacka queue
Goesone 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 in unweighted graphs, levels
Spanning treetall and thinshort and wide

Exams ask the same as for BFS, "write the DFS order from v": unique with a matrix, following the stored order with a list. Also common: "how many DFS calls does it take to visit all of an undirected graph on n vertices" = the number of connected components; "the space complexity of recursive DFS" = O(n), n levels deep 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 <iostream>2#include <stack>3using namespace std;4 5const int N = 4;6 7int a[N][N], seen[N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11int main() {12    add(0, 1); add(0, 2); add(1, 3); add(2, 3);13    stack<int> st;14    st.push(0);15    while (!st.empty()) {16        int u = st.top();17        st.pop();18        if (seen[u]) continue;19        seen[u] = 1;20        cout << u << " ";21        for (int v = 0; v < N; v++)22            if (a[u][v] && !seen[v])23                st.push(v);24    }25    cout << "\n";26    return 0;27}
Exercise 2

DFS with a stack

Fill in the while loop: take the top u; skip it if seen; otherwise mark it, print it, and push its unseen neighbours from high to low. The order printed must match recursive DFS.

It should print
0 1 3 2 5 4
exercise2.cpp
1#include <iostream>2#include <stack>3using namespace std;4 5const int N = 6;6 7int a[N][N], seen[N];8 9void add(int u, int v) { a[u][v] = a[v][u] = 1; }10 11int main() {12    add(0, 1); add(0, 2); add(1, 3); add(2, 3); add(3, 4); add(2, 5);13    stack<int> st;14    st.push(0);15    while (!st.empty()) {16        int u = st.top();17        st.pop();18        // if seen, continue; otherwise mark and print u, then v from N - 1 down to 0: push unseen neighbours19    }20    cout << '\n';21    return 0;22}
Output
Press Run or Ctrl+Enter

With the STL

On a vector<vector<int>>, DFS is usually written one of two ways: the recursive function as a lambda held in a function<void(int)>, so it can use adj and comp right inside main with no globals; or a stack<int> with no recursion. Here are both, on the graph from the components section:

main.cpp
1#include <iostream>2#include <vector>3#include <stack>4#include <functional>5using namespace std;6 7int main() {8    int n = 8;9    int edges[6][2] = {{0, 1}, {1, 2}, {3, 4}, {5, 6}, {5, 7}, {6, 7}};10    vector<vector<int>> adj(n);11    for (auto& e : edges) {12        adj[e[0]].push_back(e[1]);13        adj[e[1]].push_back(e[0]);14    }15 16    vector<int> comp(n, 0);              // 0: not seen yet; otherwise which piece17    function<void(int, int)> dfs = [&](int u, int id) {18        comp[u] = id;19        for (int v : adj[u])20            if (comp[v] == 0) dfs(v, id);21    };22    int count = 0;23    for (int i = 0; i < n; i++)24        if (comp[i] == 0) dfs(i, ++count);25    cout << count << " pieces: ";26    for (int i = 0; i < n; i++) cout << comp[i] << ' ';27    cout << '\n';28 29    vector<int> seen(n, 0);              // the same walk with a stack<int>30    stack<int> st;31    st.push(5);32    cout << "from 5: ";33    while (!st.empty()) {34        int u = st.top();35        st.pop();36        if (seen[u]) continue;37        seen[u] = 1;38        cout << u << ' ';39        for (int i = (int)adj[u].size() - 1; i >= 0; i--)   // push backwards: first neighbour on top40            if (!seen[adj[u][i]]) st.push(adj[u][i]);41    }42    cout << '\n';43    return 0;44}
Output
3 pieces: 1 1 1 2 2 3 3 3 
from 5: 5 6 7 

A lambda can't call itself by name, so declare function<void(int, int)> dfs first and let the lambda capture dfs itself with [&]. Each call through function costs a little more than a plain function; for a big graph under a time limit, write a plain function with global arrays.

What's inside: stack<int> is an adaptor like queue<int>, wrapping a deque<int> by default and opening only one end: push is push_back, top is back, pop is pop_back.

OperationCodeCost
Pushst.push(v)O(1)
Look at the topst.top()O(1)
Popst.pop() (returns nothing)O(1)
Recursive DFSfunction<void(int)> or a plain functionO(n + e), recursion up to n deep
Non-recursive DFSstack<int>O(n + e), up to O(e) on the stack

In interviews: "number of islands", "how many friend circles", "are these two points connected" are all counting connected components; DFS or BFS both work, DFS is shortest. On a grid, replace adj with the four cells around, and you can overwrite visited cells with '0' instead of keeping a seen array. If the interviewer asks "what if the graph has 10⁶ vertices?", the answer is that recursion may overflow the stack, so switch to a stack<int> or BFS.

Choose one

Why declare function<void(int, int)> dfs first and then put the lambda in it? Couldn't you just write auto dfs = [&](int u, int id) { … dfs(v, id); … };?

Summary

Take-away

DFS: one path to the end, then back

  • Recursive: mark u, then dfs straight into each unseen neighbour
  • Counting pieces: go through them all; an unseen vertex starts a new piece
  • Cycle in an undirected graph: a seen neighbour that isn't the parent
  • Without recursion: a stack<int>, mark when popped, push neighbours high to low
1function<void(int)> dfs = [&](int u) {2    seen[u] = 1;3    for (int v : adj[u])4        if (!seen[v]) dfs(v);5};