TExcelTAD
Home › Graph Algorithms › Classifying the Edges of a DFS

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 GG and let GπG_\pi be its depth-first forest (the parent edges). Every edge (u,v)(u, v) of GG is one of:

Kind Definition Colour of vv when (u,v)(u, v) is explored
tree edge an edge of the forest: vv was discovered by exploring (u,v)(u, v) white
back edge vv is an ancestor of uu in the forest (self-loops count as back edges) gray
forward edge a non-tree edge where vv is a proper descendant of uu black, and u.d<v.du.d < v.d
cross edge everything else: uu and vv are in different branches or different trees black, and u.d>v.du.d > v.d

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 uu. A gray vv is therefore an ancestor of uu. A black vv was finished before; it is a descendant of uu if uu was discovered before it (uu is still gray, so vv must lie in its subtree by the parenthesis theorem), and otherwise it lies in an earlier, finished branch.

text
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 = BLACK

The extra work is O(1)O(1) per edge, so classification is free: DFS still runs in Θ(V+E)\Theta(V + E).

The example graph again

This is the directed graph of the previous lesson. Its eleven edges include all four kinds.

python · try it yourself
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 (AA's [1,12][1, 12] contains DD's [5,6][5, 6]). A back edge goes to an interval that contains the current one (CC's [3,4][3, 4] lies inside AA's). A cross edge goes to an interval that is disjoint and earlier (D→CD \to C: [5,6][5, 6] after [3,4][3, 4]; G→FG \to F points into the finished first tree). A cross edge never points forward in time: if vv were still white when (u,v)(u, v) was explored, the edge would have become a tree edge.

Undirected graphs: only tree and back edges

In an undirected graph each edge {u,v}\{u, v\} 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 {u,v}\{u, v\} be an edge and suppose without loss of generality that u.d<v.du.d < v.d. Then vv is discovered while uu is gray, and vv is finished before uu is (it lies in uu's subtree, because uu cannot finish while its neighbour vv is still white). Consider the first time the edge is explored. If it is explored from uu, then vv is still white at that moment, since otherwise the edge would already have been explored from vv; so it becomes a tree edge. If it is explored first from vv, then uu 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.

python · try it yourself
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 V−1V - 1 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 (u,v)(u, v) plus the tree path from vv down to uu 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.

python · try it yourself
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.

cpp · try it yourself
#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 (u,v)(u, v) and finds vv gray. What kind of edge is it?

  1. Tree edge
  2. Back edge
  3. Forward edge
  4. Cross edge

DFS explores (u,v)(u, v) and finds vv black with v.d>u.dv.d > u.d. What kind of edge is it?

  1. Tree edge
  2. Back edge
  3. Forward edge
  4. Cross edge

Which edge kinds can a DFS of an undirected graph produce?

  1. All four
  2. Tree and back edges only
  3. Tree and cross edges only
  4. Tree edges only

Can a cross edge (u,v)(u, v) have v.d>u.dv.d > u.d?

  1. Yes, always
  2. No: vv would be a descendant of uu, making the edge a forward edge
  3. Only in undirected graphs
  4. Only if vv is the root