The Parenthesis and White-Path Theorems
Write an opening bracket "(u" when depth-first search discovers and a closing bracket "u)" when it finishes . The result is always a correctly nested expression, like a well-formed arithmetic formula. That is the parenthesis theorem, and together with the white-path theorem, which says exactly which vertices end up below in the depth-first forest, it is the tool behind every DFS-based proof in this course: cycle detection, topological sort and strongly connected components.
The parenthesis theorem
Theorem (parenthesis structure). In any DFS of a directed or undirected graph, for any two vertices and , exactly one of the following holds:
- the intervals and are disjoint, and neither vertex is a descendant of the other in the depth-first forest;
- lies entirely inside , and is a descendant of ;
- lies entirely inside , and is a descendant of .
Two intervals never partly overlap.
Proof
Assume (the other case is symmetric). Case : was discovered while was gray, so was on the recursion path at that moment and is a descendant of . Since was discovered after , DFS-VISIT is a call nested inside DFS-VISIT, and a nested call returns first: . So , which is case 3. Case : then , so the intervals are disjoint. Neither vertex was gray while the other was discovered, so neither is an ancestor of the other: case 1.
Corollary (nesting of descendants). is a proper descendant of if and only if .
The program prints the bracket sequence for the example graph of the DFS lesson and then checks the theorem on every pair of vertices of 300 random directed graphs.
import random
def dfs(adj):
d, f, parent, events, time = {}, {}, {}, [], 0
def visit(u):
nonlocal time
time += 1; d[u] = time; events.append(f"({u}")
for v in adj[u]:
if v not in d:
parent[v] = u
visit(v)
time += 1; f[u] = time; events.append(f"{u})")
for u in adj:
if u not in d:
visit(u)
return d, f, parent, events
adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
print(" ".join(dfs(adj)[3]))
def is_descendant(parent, v, u): # walk up from v looking for u
while v in parent:
v = parent[v]
if v == u:
return True
return False
rng = random.Random(5)
pairs = nested = disjoint = 0
for trial in range(300):
n = rng.randint(2, 15)
g = {u: [v for v in range(n) if v != u and rng.random() < 0.2] for u in range(n)}
d, f, parent, _ = dfs(g)
for u in g:
for v in g:
if u == v:
continue
pairs += 1
inside = d[u] < d[v] < f[v] < f[u]
apart = f[u] < d[v] or f[v] < d[u]
assert inside or apart or (d[v] < d[u] < f[u] < f[v]) # never a partial overlap
assert inside == is_descendant(parent, v, u) # the corollary
nested += inside
disjoint += apart
print(f"{pairs} ordered pairs: {nested} with v inside u, {nested} with u inside v, {disjoint} disjoint, 0 partial overlaps")(A (B (C C) (D D) B) (E (F F) E) A) (G G)
22872 ordered pairs: 6158 with v inside u, 6158 with u inside v, 10556 disjoint, 0 partial overlaps
The white-path theorem
Which vertices become descendants of ? Not simply the ones reachable from : in the example, is reachable from , but it is a descendant of , because was already black when was discovered. The precise answer looks at the moment is discovered.
Theorem (white path). In a depth-first forest of a (directed or undirected) graph, is a descendant of if and only if at time there is a path from to consisting entirely of white vertices (apart from itself, which has just turned gray).
Proof
Only if. If the path is just . If is a proper descendant, then by the corollary, so is white at time . The same holds for every vertex on the tree path from to , since each is a descendant of . So the tree path is a white path.
If. Suppose there is a white path from to at time , but does not become a descendant of . Among the vertices of the path that do not become descendants, let be the one closest to , and let be its predecessor on the path. Then is a descendant of (possibly itself), so . Because was white at time , . DFS cannot finish while its neighbour is still white, so . So : is discovered while is gray. By the parenthesis theorem its interval must then lie inside 's, so is a descendant of , a contradiction.
A vertex is white at time exactly when its discovery time is later than . So the theorem can be checked directly: is a descendant of if and only if is reachable from using only vertices with .
import random
def dfs(adj):
d, f, parent, time = {}, {}, {}, 0
def visit(u):
nonlocal time
time += 1; d[u] = time
for v in adj[u]:
if v not in d:
parent[v] = u
visit(v)
time += 1; f[u] = time
for u in adj:
if u not in d:
visit(u)
return d, f, parent
def white_reachable(adj, d, u):
"""Vertices reachable from u through vertices that were still white at time d[u]."""
seen, stack = {u}, [u]
while stack:
x = stack.pop()
for y in adj[x]:
if y not in seen and d[y] > d[u]:
seen.add(y)
stack.append(y)
return seen
rng = random.Random(12)
checked = 0
for trial in range(300):
n = rng.randint(2, 15)
g = {u: [v for v in range(n) if v != u and rng.random() < 0.2] for u in range(n)}
d, f, parent = dfs(g)
for u in g:
descendants = {v for v in g if d[u] <= d[v] and f[v] <= f[u]} # by the corollary
assert descendants == white_reachable(g, d, u)
checked += 1
print(f"white-path theorem confirmed for {checked} vertices in 300 random graphs")
adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
d, f, _ = dfs(adj)
for u in "BEG":
print(f"white path from {u} at time {d[u]}: {sorted(white_reachable(adj, d, u))}")white-path theorem confirmed for 2563 vertices in 300 random graphs
white path from B at time 2: ['B', 'C', 'D']
white path from E at time 8: ['E', 'F']
white path from G at time 13: ['G']
At time , vertices , and are already black, so the only white path from leads to : 's subtree is . When is discovered, everything else is black and its subtree is just .
Application: cycles and back edges
Theorem. A directed graph is acyclic if and only if a DFS of produces no back edges.
Proof
A back edge gives a cycle. If is a back edge, is an ancestor of , so the tree path from to followed by is a cycle.
A cycle gives a back edge. Let be a cycle and its vertex discovered first, and let be the edge of entering . At time all other vertices of are white, so the rest of the cycle is a white path from to . By the white-path theorem becomes a descendant of , so when DFS explores , is an ancestor of that is still gray: a back edge.
The proof does not depend on the order in which DFS picks its start vertices or neighbours: every DFS of a cyclic graph finds a back edge. That is why one search decides whether a dependency graph can be scheduled at all, the first step of topological sorting.
Test yourself
DFS gives the interval . Which interval is impossible for another vertex ?
At the moment is discovered, is reachable from , but every path from to passes through a black vertex. Is a descendant of ?
- Yes, always
- Not necessarily; by the white-path theorem it is a descendant only if a path of white vertices exists
- Only in undirected graphs
- Only if is gray
In the proof that a cycle forces a back edge, which vertex of the cycle is chosen?
- The one with the largest finishing time
- The first vertex of the cycle that DFS discovers
- The vertex with the smallest name
- The last vertex finished