Classifying the Edges of a DFS
A depth-first search does not just visit vertices; it looks at every edge exactly once (twice in an undirected graph) and, at that moment, knows the colour of the vertex at the other end. That colour sorts the edges into four kinds, and the kinds answer real questions. A directed graph has a cycle exactly when DFS meets a back edge; an undirected graph never has forward or cross edges; and the edge kinds are the raw material of the strongly connected components algorithms. This lesson defines the four kinds, shows how DFS tells them apart from colours and timestamps, and proves the rule for undirected graphs.
The four kinds
Run DFS on and let be its depth-first forest (the parent edges). Every edge of is one of:
| Kind | Definition | Colour of when is explored |
|---|---|---|
| tree edge | an edge of the forest: was discovered by exploring | white |
| back edge | is an ancestor of in the forest (self-loops count as back edges) | gray |
| forward edge | a non-tree edge where is a proper descendant of | black, and |
| cross edge | everything else: and are in different branches or different trees | black, and |
The colour column works because the gray vertices at any moment are exactly the vertices on the current recursion path, from the root of the current tree down to . A gray is therefore an ancestor of . A black was finished before; it is a descendant of if was discovered before it ( is still gray, so must lie in its subtree by the parenthesis theorem), and otherwise it lies in an earlier, finished branch.
DFS-VISIT(G, u) // with edge classification
1 time = time + 1; u.d = time; u.color = GRAY
2 for each v in G.Adj[u]
3 if v.color == WHITE
4 classify (u, v) as a tree edge; v.pi = u; DFS-VISIT(G, v)
5 elseif v.color == GRAY
6 classify (u, v) as a back edge
7 elseif u.d < v.d
8 classify (u, v) as a forward edge
9 else
10 classify (u, v) as a cross edge
11 time = time + 1; u.f = time; u.color = BLACKThe extra work is per edge, so classification is free: DFS still runs in .
The example graph again
This is the directed graph of the previous lesson. Its eleven edges include all four kinds.
adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
def classify(adj):
color = {u: "white" for u in adj}
d, f, kinds = {}, {}, {}
time = 0
def visit(u):
nonlocal time
time += 1; d[u] = time; color[u] = "gray"
for v in adj[u]:
if color[v] == "white":
kinds[(u, v)] = "tree"
visit(v)
elif color[v] == "gray":
kinds[(u, v)] = "back"
elif d[u] < d[v]:
kinds[(u, v)] = "forward"
else:
kinds[(u, v)] = "cross"
time += 1; f[u] = time; color[u] = "black"
for u in sorted(adj):
if color[u] == "white":
visit(u)
return d, f, kinds
d, f, kinds = classify(adj)
for (u, v), k in kinds.items():
print(f"{u}->{v}: {k:8} [{d[u]:2}, {f[u]:2}] vs [{d[v]:2}, {f[v]:2}]")A->B: tree [ 1, 12] vs [ 2, 7]
B->C: tree [ 2, 7] vs [ 3, 4]
C->A: back [ 3, 4] vs [ 1, 12]
B->D: tree [ 2, 7] vs [ 5, 6]
D->C: cross [ 5, 6] vs [ 3, 4]
A->D: forward [ 1, 12] vs [ 5, 6]
A->E: tree [ 1, 12] vs [ 8, 11]
E->D: cross [ 8, 11] vs [ 5, 6]
E->F: tree [ 8, 11] vs [ 9, 10]
F->E: back [ 9, 10] vs [ 8, 11]
G->F: cross [13, 14] vs [ 9, 10]
Every kind shows up in the intervals. A tree or forward edge goes from an interval to one nested inside it ('s contains 's ). A back edge goes to an interval that contains the current one ('s lies inside 's). A cross edge goes to an interval that is disjoint and earlier (: after ; points into the finished first tree). A cross edge never points forward in time: if were still white when was explored, the edge would have become a tree edge.
Undirected graphs: only tree and back edges
In an undirected graph each edge appears in both adjacency lists, so DFS meets it twice. Classify it by whichever direction is explored first.
Theorem. In a DFS of an undirected graph, every edge is a tree edge or a back edge.
Proof
Let be an edge and suppose without loss of generality that . Then is discovered while is gray, and is finished before is (it lies in 's subtree, because cannot finish while its neighbour is still white). Consider the first time the edge is explored. If it is explored from , then is still white at that moment, since otherwise the edge would already have been explored from ; so it becomes a tree edge. If it is explored first from , then is gray at that moment, so the edge is a back edge. Forward and cross edges need a black endpoint at the first exploration, which cannot happen.
The program classifies the edges of 300 random undirected graphs by their first exploration and counts the kinds.
import random
def classify_undirected(adj):
color, d, seen_edges = {u: "white" for u in adj}, {}, set()
counts = {"tree": 0, "back": 0, "forward": 0, "cross": 0}
time = 0
def visit(u):
nonlocal time
time += 1; d[u] = time; color[u] = "gray"
for v in adj[u]:
e = frozenset((u, v))
if e in seen_edges:
continue # second sighting of the same edge
seen_edges.add(e)
if color[v] == "white":
counts["tree"] += 1; visit(v)
elif color[v] == "gray":
counts["back"] += 1
elif d[u] < d[v]:
counts["forward"] += 1
else:
counts["cross"] += 1
color[u] = "black"
for u in adj:
if color[u] == "white":
visit(u)
return counts
rng = random.Random(31)
total = {"tree": 0, "back": 0, "forward": 0, "cross": 0}
for trial in range(300):
n = rng.randint(2, 20)
adj = {u: [] for u in range(n)}
for u in range(n):
for v in range(u + 1, n):
if rng.random() < 0.2:
adj[u].append(v); adj[v].append(u)
for k, c in classify_undirected(adj).items():
total[k] += c
print(total){'tree': 2525, 'back': 1413, 'forward': 0, 'cross': 0}
Every non-tree edge is a back edge, so an undirected graph has a cycle exactly when DFS finds a back edge, and a connected undirected graph is a tree exactly when DFS finds tree edges and nothing else.
Finding a cycle in a directed graph
The same test works for directed graphs: a directed graph is acyclic if and only if DFS finds no back edge. One direction is immediate: a back edge plus the tree path from down to is a cycle. The other direction ("a cycle forces a back edge") needs the white-path theorem and is proved in the next lesson. The program uses the parent pointers to print the cycle that a back edge closes. The DSA course shows the same check with a "currently on the path" set.
def find_cycle(adj):
color, parent = {u: "white" for u in adj}, {}
def visit(u):
color[u] = "gray"
for v in adj[u]:
if color[v] == "white":
parent[v] = u
found = visit(v)
if found:
return found
elif color[v] == "gray": # back edge u -> v
cycle, x = [u], u
while x != v:
x = parent[x]
cycle.append(x)
return list(reversed(cycle)) + [v]
color[u] = "black"
return None
for u in sorted(adj):
if color[u] == "white":
found = visit(u)
if found:
return found
return None
dag = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": []}
cyclic = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": ["B"]}
print("dag: ", find_cycle(dag))
print("cyclic:", " -> ".join(find_cycle(cyclic)))dag: None
cyclic: B -> D -> E -> B
In C++
The C++ version classifies the edges of the example graph with colours stored as small integers.
#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}};
enum { WHITE, GRAY, BLACK };
std::vector<int> color(n, WHITE), d(n, 0);
int time = 0, counts[4] = {0, 0, 0, 0};
const char* kind[4] = {"tree", "back", "forward", "cross"};
std::function<void(int)> visit = [&](int u) {
d[u] = ++time;
color[u] = GRAY;
for (int v : adj[u]) {
int k = color[v] == WHITE ? 0 : color[v] == GRAY ? 1 : d[u] < d[v] ? 2 : 3;
std::printf("%c->%c %s\n", names[u], names[v], kind[k]);
++counts[k];
if (k == 0) visit(v);
}
++time;
color[u] = BLACK;
};
for (int u = 0; u < n; ++u)
if (color[u] == WHITE) visit(u);
std::printf("tree %d, back %d, forward %d, cross %d\n", counts[0], counts[1], counts[2], counts[3]);
}A->B tree
B->C tree
C->A back
B->D tree
D->C cross
A->D forward
A->E tree
E->D cross
E->F tree
F->E back
G->F cross
tree 5, back 2, forward 1, cross 3
Test yourself
DFS explores edge and finds gray. What kind of edge is it?
- Tree edge
- Back edge
- Forward edge
- Cross edge
DFS explores and finds black with . What kind of edge is it?
- Tree edge
- Back edge
- Forward edge
- Cross edge
Which edge kinds can a DFS of an undirected graph produce?
- All four
- Tree and back edges only
- Tree and cross edges only
- Tree edges only
Can a cross edge have ?
- Yes, always
- No: would be a descendant of , making the edge a forward edge
- Only in undirected graphs
- Only if is the root