Depth-First Search: Discovery and Finishing Times
Breadth-first search spreads out in waves. Depth-first search (DFS) does the opposite: it follows one path as far as it can, and only when it gets stuck does it back up to the most recent vertex with an unexplored edge. It is how you would explore a maze with a ball of string. DFS computes no distances, but it records when it first reaches each vertex and when it is done with it. Those two timestamps carry a remarkable amount of structure: they classify the edges, detect cycles, sort a DAG topologically and find strongly connected components, the subjects of the next lessons. The DSA course has a first look at DFS; here it gets the timestamps.
The algorithm
DFS keeps a global clock time. Each vertex gets a discovery time , when it is first reached, and a finishing time , when its adjacency list has been fully examined. Every vertex is white (undiscovered) before , gray (discovered, not finished) between and , and black (finished) after. The outer loop starts a new search from every vertex that is still white, so DFS visits every vertex, unlike a BFS from one source.
DFS(G)
1 for each vertex u in G.V
2 u.color = WHITE; u.pi = NIL
3 time = 0
4 for each vertex u in G.V // alphabetical order
5 if u.color == WHITE
6 DFS-VISIT(G, u)
DFS-VISIT(G, u)
1 time = time + 1; u.d = time; u.color = GRAY
2 for each v in G.Adj[u] // alphabetical order
3 if v.color == WHITE
4 v.pi = u
5 DFS-VISIT(G, v)
6 time = time + 1; u.f = time; u.color = BLACKEach vertex is discovered once and finished once, so the timestamps are the integers to , each used once, and for every .
Watching it work
The directed graph below has seven vertices. The animation follows DFS-VISIT from : the highlighted path is the stack of gray vertices, and the run stops when finishes. Vertex cannot be reached from ; the outer loop of DFS starts a second tree there.
The Python version prints every discovery and finish with its timestamp, then the parent pointers and the intervals .
adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
def dfs(adj):
color = {u: "white" for u in adj}
d, f, pi = {}, {}, {u: None for u in adj}
time = 0
def visit(u, depth):
nonlocal time
time += 1
d[u], color[u] = time, "gray"
print(f"{' ' * depth}discover {u} at {time}")
for v in sorted(adj[u]):
if color[v] == "white":
pi[v] = u
visit(v, depth + 1)
time += 1
f[u], color[u] = time, "black"
print(f"{' ' * depth}finish {u} at {time}")
for u in sorted(adj):
if color[u] == "white":
print(f"new tree rooted at {u}")
visit(u, 1)
return d, f, pi
d, f, pi = dfs(adj)
print("parents:", {v: p for v, p in pi.items() if p})
print("intervals:", ", ".join(f"{u} [{d[u]}, {f[u]}]" for u in sorted(adj)))new tree rooted at A
discover A at 1
discover B at 2
discover C at 3
finish C at 4
discover D at 5
finish D at 6
finish B at 7
discover E at 8
discover F at 9
finish F at 10
finish E at 11
finish A at 12
new tree rooted at G
discover G at 13
finish G at 14
parents: {'B': 'A', 'C': 'B', 'D': 'B', 'E': 'A', 'F': 'E'}
intervals: A [1, 12], B [2, 7], C [3, 4], D [5, 6], E [8, 11], F [9, 10], G [13, 14]
The indentation is the recursion depth, which is also the depth in the depth-first forest: the parent edges form one tree rooted at (with ) and a second tree that is just , since everything points to is already black when the outer loop reaches it. The order of the outer loop and of each adjacency list changes the forest and the timestamps, but not the properties proved in the next lessons.
Running time
The outer loop and the initialization cost . DFS-VISIT is called exactly once per vertex, because it is called only on white vertices and immediately paints them gray. Inside the call for , the loop over runs times, and summed over all vertices that is . So DFS runs in time, the same as BFS, but it always covers the whole graph.
Recursion depth and an iterative version
The recursion can go as deep as : on a path every vertex is gray at once. Python's default recursion limit is 1000 frames, so the recursive version fails on a path of a few thousand vertices. The iterative version keeps an explicit stack of (vertex, position in its adjacency list) pairs, which reproduces the recursive order and timestamps exactly. The program checks that both versions agree on 200 small random graphs, then runs the iterative one on a path of 20,000 vertices.
import random
def dfs_recursive(adj):
d, f, time = {}, {}, 0
def visit(u):
nonlocal time
time += 1; d[u] = time
for v in adj[u]:
if v not in d:
visit(v)
time += 1; f[u] = time
for u in adj:
if u not in d:
visit(u)
return d, f
def dfs_iterative(adj):
d, f, time, deepest = {}, {}, 0, 0
for s in adj:
if s in d:
continue
time += 1; d[s] = time
stack = [(s, 0)] # vertex and index of its next neighbour
while stack:
deepest = max(deepest, len(stack))
u, i = stack[-1]
if i < len(adj[u]):
stack[-1] = (u, i + 1)
v = adj[u][i]
if v not in d:
time += 1; d[v] = time
stack.append((v, 0))
else:
stack.pop()
time += 1; f[u] = time
return d, f, deepest
rng = random.Random(8)
for trial in range(200):
n = rng.randint(1, 25)
adj = {u: sorted(v for v in range(n) if v != u and rng.random() < 0.15) for u in range(n)}
d1, f1 = dfs_recursive(adj)
d2, f2, _ = dfs_iterative(adj)
assert (d1, f1) == (d2, f2)
print("recursive and iterative DFS agree on 200 random graphs")
n = 20000
path = {i: [i + 1] if i + 1 < n else [] for i in range(n)}
d, f, deepest = dfs_iterative(path)
print(f"path of {n} vertices: d[0] = {d[0]}, f[0] = {f[0]}, deepest stack = {deepest}")
try:
dfs_recursive(path)
except RecursionError:
print("the recursive version raises RecursionError on the same path")recursive and iterative DFS agree on 200 random graphs
path of 20000 vertices: d[0] = 1, f[0] = 40000, deepest stack = 20000
the recursive version raises RecursionError on the same path
In C++
C++ has a much larger call stack than Python's limit, so a recursive DFS is fine for graphs of moderate depth; for millions of vertices in a path, use the explicit stack. The program runs the recursive version on the graph of the animation and prints the same timestamps and forest.
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
int main() {
const std::string names = "ABCDEFG";
const int n = static_cast<int>(names.size());
std::vector<std::vector<int>> adj = {{1, 3, 4}, {2, 3}, {0}, {2}, {3, 5}, {4}, {5}}; // A..G, sorted lists
std::vector<int> d(n, 0), f(n, 0), pi(n, -1);
int time = 0;
std::function<void(int)> visit = [&](int u) {
d[u] = ++time;
for (int v : adj[u])
if (d[v] == 0) { pi[v] = u; visit(v); }
f[u] = ++time;
};
for (int u = 0; u < n; ++u)
if (d[u] == 0) {
std::printf("tree rooted at %c\n", names[u]);
visit(u);
}
for (int u = 0; u < n; ++u)
std::printf("%c: [%2d, %2d] parent %c\n", names[u], d[u], f[u], pi[u] < 0 ? '-' : names[pi[u]]);
}tree rooted at A
tree rooted at G
A: [ 1, 12] parent -
B: [ 2, 7] parent A
C: [ 3, 4] parent B
D: [ 5, 6] parent B
E: [ 8, 11] parent A
F: [ 9, 10] parent E
G: [13, 14] parent -
Test yourself
A directed graph has 9 vertices. Which numbers are used as DFS timestamps?
- to
- to , each twice
- to , each exactly once
- It depends on the number of edges
In the lesson's run, why does form a tree of its own?
- has no outgoing edges
- No vertex discovered from has an edge to , so the outer loop starts a new search at
- is gray when finishes
- Because comes last alphabetically
What is the running time of DFS with adjacency lists?
- always
Why does the recursive Python DFS fail on a path of 20,000 vertices?
- DFS is exponential on paths
- The recursion depth equals the number of gray vertices, up to , which exceeds Python's default limit of 1000 frames
- Paths have cycles
- Python sorts the adjacency lists