Sub topic 7
Classifying DFS Edges
This chapter assumes you can read recursive Python, know how depth-first search (DFS) visits vertices, and remember the white/gray/black vocabulary from the DFS refresher. The goal is to sort every edge DFS examines into one of four kinds. The next chapter's directed cycle detector is built on one of those kinds, the back edge, so this sorting is what that detector relies on.
Why classify edges at all
When DFS examines an edge (u, v), it sees one of three things at the far end: an unvisited vertex, a vertex still in progress, or a finished vertex. A naive cycle detector reports a cycle whenever it reaches an already-visited vertex. That works for undirected graphs once you handle the parent edge correctly. In directed graphs it gives false positives, because reaching a visited vertex does not always mean a cycle. Edge classification tells you exactly which visited-vertex edges mean a cycle.
The four edge types
DFS builds a forest. Each tree is rooted at a vertex where the outer loop started a new search. Each edge (u, v) falls into one of these kinds relative to that forest:
| Type | Meaning | State of `v` when `(u, v)` is examined |
|---|---|---|
| Tree edge | DFS discovered `v` through this edge | White (unvisited) |
| Back edge | `v` is an ancestor of `u` (or `v == u`) | Gray (on the current path) |
| Forward edge | `v` is a proper descendant of `u`, but not through this edge | Black, discovered after `u` |
| Cross edge | `v` is neither ancestor nor descendant of `u` | Black, discovered before `u` |
A self-loop (u, u) counts as a back edge. When DFS examines it, u is gray, and a vertex counts as its own ancestor.
Timestamps and the parenthesis structure
Colors are enough to separate tree and back edges from the rest. A black v could still be either a forward or a cross target. To tell those apart, record two timestamps per vertex: d[v] when DFS discovers v (turns it gray) and f[v] when DFS finishes it (turns it black). One shared counter increases at each event.
These intervals obey the parenthesis theorem. For any two vertices, their intervals [d, f] are either disjoint or one contains the other. They never partially overlap. Interval containment means ancestry: u is an ancestor of v exactly when [d[v], f[v]] lies inside [d[u], f[u]].
The edge types then correspond to interval relationships:
| Type | Interval relationship for edge `(u, v)` |
|---|---|
| Tree or forward | `d[u] < d[v] < f[v] < f[u]` |
| Back | `d[v] <= d[u] < f[u] <= f[v]` |
| Cross | `d[v] < f[v] < d[u] < f[u]` |
Cross edges always point from a later-discovered vertex to an earlier-discovered one, into a subtree that has already finished. An edge can never point from a finished subtree into a later, not-yet-discovered region. If it did, DFS would have followed it before finishing.
A working classifier
The function below runs DFS over every component of a directed graph given as an adjacency list. It returns each edge with its type, plus the timestamp arrays.
WHITE, GRAY, BLACK = 0, 1, 2
def classify_edges(adj):
n = len(adj)
color = [WHITE] * n
d = [0] * n
f = [0] * n
time = 0
edges = []
def dfs(u):
nonlocal time
time += 1
d[u] = time
color[u] = GRAY
for v in adj[u]:
if color[v] == WHITE:
edges.append((u, v, "tree"))
dfs(v)
elif color[v] == GRAY:
edges.append((u, v, "back"))
elif d[u] < d[v]:
edges.append((u, v, "forward"))
else:
edges.append((u, v, "cross"))
color[u] = BLACK
time += 1
f[u] = time
for s in range(n):
if color[s] == WHITE:
dfs(s)
return edges, d, f
adj = [
[1, 2, 3], # 0
[2], # 1
[0], # 2
[2], # 3
[4], # 4 has a self-loop
]
edges, d, f = classify_edges(adj)
for u, v, kind in edges:
print(f"({u}, {v}) {kind}")
print("d =", d)
print("f =", f)Output:
(0, 1) tree
(1, 2) tree
(2, 0) back
(0, 2) forward
(0, 3) tree
(3, 2) cross
(4, 4) back
d = [1, 2, 3, 6, 9]
f = [8, 5, 4, 7, 10]Trace the important moments:
- DFS goes 0 → 1 → 2 along tree edges. At vertex 2, the edge to 0 finds 0 gray, so it is a back edge. The cycle 0 → 1 → 2 → 0 exists.
- Vertex 2 finishes at time 4, then vertex 1 at time 5. Back at 0, the edge
(0, 2)finds 2 black withd[0] = 1 < d[2] = 3. Vertex 2 is a descendant of 0, so this is a forward edge. - DFS reaches 3 by a tree edge. The edge
(3, 2)finds 2 black withd[3] = 6 > d[2] = 3. Vertex 2 sits in a subtree that finished before 3 was discovered, so this is a cross edge. - Vertex 4 starts a new DFS tree. Its self-loop sees 4 gray, so it is a back edge.
Only the back edges sit on cycles. The forward edge (0, 2) and the cross edge (3, 2) both reach an already-visited vertex, but neither closes a cycle. The edge (0, 2) happens to share vertices with a cycle, yet removing every back edge leaves an acyclic graph. A detector that flags "any edge to a visited vertex" would wrongly report a cycle from the cross edge (3, 2) even if (2, 0) were deleted.
The back-edge theorem
A directed graph has a cycle if and only if DFS produces at least one back edge.
- Back edge implies cycle. If
(u, v)is a back edge,vis an ancestor ofu. The tree path fromvdown tou, followed by the edge(u, v), is a cycle. For a self-loop, the path is empty and the edge alone is the cycle. - Cycle implies back edge. Take any cycle, and let
vbe the first of its vertices that DFS discovers. Letube the vertex beforevon the cycle. At timed[v], every other cycle vertex is white, so a path of white vertices runs fromvtou. By the white-path theorem,ubecomes a descendant ofv. Whileuis being explored,vis still gray, so(u, v)is a back edge.
For pure cycle detection you only need to recognize back edges, and the gray check does that. Timestamps matter only when you need the full four-way classification, for example to tell forward from cross edges.
Undirected graphs: only tree and back edges
In an undirected DFS, every edge is either a tree edge or a back edge. Take an edge {u, v} with d[u] < d[v]. Vertex u cannot finish before it scans its neighbor v, so v is discovered while u is still gray. That makes v a descendant of u. If DFS first traverses the edge from u, then v is white and the edge is a tree edge. If DFS first traverses it from v, then u is gray and the edge is a back edge. A forward or cross classification would require the edge to be seen first from a finished or unrelated vertex, and that cannot happen.
Each undirected edge appears twice in an adjacency list, so you classify it by the direction DFS traverses first. Two consequences link this to the earlier chapters:
- When DFS at
vlooks back along the tree edge it arrived on, the parent is gray. Without parent-edge tracking, that looks like a back edge, and this is exactly the false positive the parent-tracking detector avoids. - When an ancestor later scans an edge to a black descendant, it is seeing the second direction of an edge that was already classified as a back edge from the descendant's side. It is not a forward edge.
Summary of decision criteria
| Question | Information needed |
|---|---|
| Does a directed graph have a cycle? | Colors only. Look for an edge into a gray vertex |
| Is a specific edge forward or cross? | Colors plus discovery times |
| Is `u` an ancestor of `v`? | Discovery and finish times (interval containment) |
| Does an undirected graph have a cycle? | Visited flags plus the parent edge. Any other edge to a visited vertex is a back edge |
Exercise
Run DFS on the directed graph with adjacency list [[1], [2], [], [1, 2]], starting from vertex 0 and then continuing from the lowest-numbered white vertex. Classify every edge and say whether the graph has a cycle.
Show answer
DFS from 0 gives tree edges (0, 1) and (1, 2). Timestamps are d = [1, 2, 3, ...] and f[2] = 4, f[1] = 5, f[0] = 6. DFS then starts at 3 with d[3] = 7. Edge (3, 1) finds 1 black with d[3] = 7 > d[1] = 2, so it is a cross edge. Edge (3, 2) is a cross edge for the same reason. There are no back edges, so the graph is acyclic, even though two edges reach already-visited vertices.
Exercise
In the chapter's example, the adjacency list for vertex 0 is reordered to [3, 2, 1]. Which edge types change, and does the back edge (2, 0) still appear?
Show answer
DFS from 0 now goes to 3 first: (0, 3) is a tree edge and (3, 2) becomes a tree edge. From 2, the edge (2, 0) finds 0 gray, so it is still a back edge. Back at 0, the edge (0, 2) finds 2 black with d[0] < d[2], so it is a forward edge. Then (0, 1) is a tree edge, and (1, 2) finds 2 black with d[1] > d[2], so it becomes a cross edge. Forward and cross labels moved between edges, but a back edge still exists, as the back-edge theorem guarantees.
Exercise
Explain why an undirected DFS can never produce a cross edge, using discovery times.
Show answer
Take an edge {u, v} with d[u] < d[v]. Vertex u stays gray until it has scanned all its neighbors, including v, so v is discovered before u finishes. That makes v a descendant of u. A cross edge needs two vertices that are not ancestor and descendant, so no undirected edge can be one.