Sub topic 9
Classifying Edges During DFS
This chapter assumes you have read the previous chapter on discovery and finish times. You should be comfortable with recursive DFS, the white/gray/black coloring of vertices, and the idea that each vertex gets a discovery time d[u] and a finish time f[u]. You also need to know the difference between directed and undirected graphs.
A DFS does more than visit vertices. Every time it examines an edge (u, v), it can label that edge by how v relates to u in the DFS forest. These labels are the basis for cycle detection, topological sorting, strongly connected components, and bridge finding, which later chapters cover. This chapter covers only the labels themselves: what they are, how to compute them, and where they mislead people.
The Four Edge Types
Suppose DFS is at vertex u and examines the edge (u, v). The edge gets one of four labels:
| Type | Meaning | Color of `v` when examined | Interval relation |
|---|---|---|---|
| Tree | DFS discovers `v` through this edge | White | `d[u] < d[v] < f[v] < f[u]` |
| Back | `v` is an ancestor of `u` (or `u` itself) | Gray | `d[v] ≤ d[u] < f[u] ≤ f[v]` |
| Forward | `v` is a descendant of `u`, but not through this edge | Black, and `d[u] < d[v]` | `d[u] < d[v] < f[v] < f[u]` |
| Cross | `v` is in a different, already finished subtree | Black, and `d[v] < d[u]` | `d[v] < f[v] < d[u] < f[u]` |
The last column uses the parenthesis theorem from the previous chapter. Tree and forward edges have the same interval shape, because in both cases v is nested inside u. You can only tell them apart by asking whether this edge is the one that discovered v.
A gray vertex is still on the recursion stack. So an edge to a gray vertex points back up the current path, which is why it is called a back edge. A self-loop (u, u) counts as a back edge, because u is gray when its own edge is examined.
The Decision Procedure
At the moment an edge is examined you know only the current colors and the discovery times assigned so far. Those are enough:
The black-vertex test works because a black vertex with a larger discovery time than u must have been discovered and finished while u was gray. That makes it a descendant of u. A black vertex with a smaller discovery time finished before u started, so it lies in a separate subtree.
Classifying Edges in a Directed Graph
The following function runs DFS over the whole graph and records a label for every edge:
WHITE, GRAY, BLACK = 0, 1, 2
def classify_edges(graph):
color = {u: WHITE for u in graph}
disc, fin = {}, {}
kinds = {}
time = 0
def visit(u):
nonlocal time
color[u] = GRAY
time += 1
disc[u] = time
for v in graph[u]:
if color[v] == WHITE:
kinds[(u, v)] = "tree"
visit(v)
elif color[v] == GRAY:
kinds[(u, v)] = "back"
elif disc[u] < disc[v]:
kinds[(u, v)] = "forward"
else:
kinds[(u, v)] = "cross"
color[u] = BLACK
time += 1
fin[u] = time
for u in graph:
if color[u] == WHITE:
visit(u)
return kinds, disc, fin
graph = {"A": ["B", "C", "D"], "B": ["C"], "C": ["A"], "D": ["C"]}
kinds, disc, fin = classify_edges(graph)
for (u, v), kind in kinds.items():
print(f"{u}->{v}: {kind}")
print(disc, fin)Output:
A->B: tree
B->C: tree
C->A: back
A->C: forward
A->D: tree
D->C: cross
{'A': 1, 'B': 2, 'C': 3, 'D': 6} {'C': 4, 'B': 5, 'D': 7, 'A': 8}Here is the trace. DFS discovers A, then B, then C along tree edges. From C, the edge to A finds A gray, so it is a back edge. C and B finish. Back at A, the edge to C finds C black with d[C] = 3 > d[A] = 1, so it is a forward edge. The edge A→D is a tree edge. From D, the edge to C finds C black with d[C] = 3 < d[D] = 6, so it is a cross edge.
Undirected Graphs: Only Tree and Back Edges
An undirected DFS produces only tree edges and back edges. The reasoning goes like this:
- No forward edges. Suppose
{u, v}connectsuto a descendantv. Whilevwas being explored,uwas gray, sovalready examined the edge from its own end and classified it as a back edge. By the timeulooks at it, the edge has a label. - No cross edges. Suppose
vfinished beforeuwas discovered. Whilevwas exploring,uwas white, sovwould have discovereduthrough this edge. That makes it a tree edge.
Each undirected edge appears twice in an adjacency list, once from each end. The classifier must ignore the second appearance. In particular, it must not label the edge back to the parent as a back edge. One simple approach keys each edge by an unordered pair:
def classify_undirected(graph):
disc = {}
kinds = {}
time = 0
def visit(u):
nonlocal time
time += 1
disc[u] = time
for v in graph[u]:
edge = frozenset((u, v))
if edge in kinds:
continue # already seen from the other end
if v not in disc:
kinds[edge] = "tree"
visit(v)
else:
kinds[edge] = "back"
for u in graph:
if u not in disc:
visit(u)
return kinds
graph = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B", "D"], "D": ["C"]}
for edge, kind in classify_undirected(graph).items():
print(f"{'-'.join(sorted(edge))}: {kind}")Output:
A-B: tree
B-C: tree
A-C: back
C-D: treeThe triangle A–B–C produces exactly one back edge, which closes the cycle. The edge C–D does not lie on any cycle and stays a tree edge.
Gotchas
Labels depend on traversal order
The same graph can produce different labels if the start vertex or the neighbor order changes. In the directed example, if A's list were ["C", "B", "D"], then A→C would be a tree edge and B→C would become a cross edge. Some properties hold for every order. The most important one is that a directed graph has a back edge in some DFS exactly when it has a back edge in every DFS, which happens exactly when the graph contains a cycle. The next chapter builds on that fact.
Visited is not enough for directed graphs
A single visited set merges gray and black into one state. Then you cannot tell a back edge, which signals a cycle, from a forward or cross edge, which does not. Undirected graphs get away with a visited set plus the parent rule. Directed graphs need all three colors, or an explicit "on the current path" set.
Iterative DFS needs explicit finish events
The iterative DFS from an earlier chapter marks a vertex visited when it is popped, and it never records when a vertex finishes. So it has no gray state, and its labels would be wrong. To classify edges iteratively, push frames of the form (vertex, neighbor_iterator). Mark a vertex black only when its iterator runs out, and handle each edge when the iterator yields it, not when the edge is pushed.
Count check
Every edge gets exactly one label. In a directed graph with E edges, the four counts add up to E. The tree edges number V − k, where k is the number of DFS trees in the forest. This check makes a useful assertion when you test a classifier.
Exercise
Run classify_edges on the graph {"1": ["2", "3"], "2": ["4"], "3": ["4"], "4": ["2"]}. Label every edge.
Show answer
DFS discovers 1 (d=1), 2 (d=2), and 4 (d=3). From 4, the edge 4->2 finds 2 gray, so it is a back edge. Vertex 4 finishes, then 2. From 1, the edge 1->3 is a tree edge (d[3]=6). From 3, the edge 3->4 finds 4 black with d[4]=3 < d[3]=6, so it is a cross edge. Result: 1->2 tree, 2->4 tree, 4->2 back, 1->3 tree, 3->4 cross.
Exercise
In a directed DFS, an edge (u, v) is examined and v is black with d[v] > d[u]. A teammate says it must be a tree edge, since v is a descendant of u. Why are they wrong?
Show answer
A tree edge is the edge through which v was discovered, and at that moment v is white. If v is already black, some other path from u reached it first, so this edge is a forward edge. The interval shapes of tree and forward edges are identical. Only the color at examination time tells them apart.
Exercise
Explain why an undirected graph with V vertices, E edges, and k connected components has exactly E − V + k back edges after a full DFS.
Show answer
An undirected DFS produces only tree and back edges, and each edge gets exactly one label. The DFS forest has one tree per component, and a tree with n vertices has n − 1 edges, so there are V − k tree edges in total. The remaining E − (V − k) = E − V + k edges must be back edges.