Skip to content

Depth-First Search / DFS

One of the ways to traverse a graph

Time Complexity

In general, on a graph \(G = (V, E)\), DFS will run in \(O(|V| + |E|)\) time.

Types

  • Pre-order
    • Process current node before children
  • Post-order
    • Process children before current node
  • In-order
    • Process in the order of: left child, current node, right child
    • Only makes sense on binary trees

Info

The distinction between (pre/post/in)-order is not that important because a lot of times we want to do processing both before and after the children are processed

Implementation

Info

There are many ways to implement DFS. This is not the only correct way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/** Runs DFS starting at u */
void dfs(int u, List<List<Integer>> adj, boolean[] visited) {
    visited[u] = true;

    for (int v : adj.get(u)) {
        if (visited[v]) {
            continue;
        }

        dfs(v, adj, visited);
    }
}

void dfs(int u, List<List<Integer>> adj) {
    int n = adj.size();
    boolean[] visited = new boolean[n];
    dfs(u, adj, visited);
}