Topological Sort by Finishing Times
A build system has to compile a library before the programs that link against it; a university wants every course scheduled after its prerequisites; a spreadsheet must recompute a cell after the cells it reads. Each is a directed acyclic graph (DAG) of tasks, with an edge meaning " must come before ", and each asks for a topological sort: a linear order of all vertices in which every edge points forward. DAGs and Scheduling in Discrete Mathematics proves that such an order exists exactly when the graph is acyclic. This lesson gets one in time from a single depth-first search, and proves that it is correct.
The algorithm
Run DFS and list the vertices in order of decreasing finishing time. In practice, push each vertex on the front of a list at the moment it finishes.
TOPOLOGICAL-SORT(G)
1 L = an empty linked list
2 run DFS(G); when a vertex v finishes, insert v at the front of L
3 if DFS found a back edge
4 report "G has a cycle, no topological order exists"
5 return LEach insertion at the front of a linked list is , so the whole procedure costs the same as DFS, .
The graph below is the plan for a small software release: = set up the repository, = write the parser, = write the core library, = test the parser, = write the plugins, = package the release, = write the documentation. The animation is the DFS from , which reaches every vertex. Watch the order in which vertices backtrack: that is the finishing order, and its reverse is the answer.
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}
def topological_sort(adj):
color = {u: "white" for u in adj}
order, time = [], 0
def visit(u):
nonlocal time
time += 1
color[u] = "gray"
for v in adj[u]:
if color[v] == "gray":
raise ValueError(f"back edge {u}->{v}: the graph has a cycle")
if color[v] == "white":
visit(v)
time += 1
color[u] = "black"
order.insert(0, u) # front of the list
print(f"finish {u} at {time:2}: list is {' '.join(order)}")
for u in sorted(adj):
if color[u] == "white":
visit(u)
return order
order = topological_sort(adj)
pos = {v: i for i, v in enumerate(order)}
print("topological order:", " ".join(order))
print("every edge points forward:", all(pos[u] < pos[v] for u in adj for v in adj[u]))
try:
topological_sort({"A": ["B"], "B": ["C"], "C": ["A"]})
except ValueError as e:
print("cyclic graph:", e)finish F at 5: list is F
finish D at 6: list is D F
finish B at 7: list is B D F
finish G at 11: list is G B D F
finish E at 12: list is E G B D F
finish C at 13: list is C E G B D F
finish A at 14: list is A C E G B D F
topological order: A C E G B D F
every edge points forward: True
cyclic graph: back edge C->A: the graph has a cycle
(packaging) finishes first because nothing depends on it; it ends up last in the order. , which everything depends on, finishes last and comes first.
Why it works
Lemma. In a DFS of a directed acyclic graph, every edge satisfies .
Proof
Consider the moment DFS explores ; is gray. Vertex cannot be gray, because then would be an ancestor of and a back edge, and a DAG has no back edges (white-path application). If is white, it becomes a descendant of , and by the parenthesis theorem . If is black, it is already finished while is not, so again .
Theorem. TOPOLOGICAL-SORT produces a topological order of a DAG.
Listing vertices by decreasing finishing time places before whenever , which by the lemma is the case for every edge . And if the graph has a cycle, every DFS finds a back edge, so the algorithm correctly reports that no order exists.
Many orders, one algorithm
A DAG usually has many topological orders: any order that respects the edges will do. DFS returns one of them, determined by the order in which it tries start vertices and neighbours. The program counts all topological orders of the release plan with a dynamic program over subsets ("how many ways to order the remaining tasks, given which ones are done") and checks the DFS answer on 500 random DAGs.
import random
from functools import lru_cache
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}
names = sorted(adj)
preds = {v: {u for u in adj if v in adj[u]} for v in names}
@lru_cache(maxsize=None)
def count(done): # done is a frozenset of finished tasks
if len(done) == len(names):
return 1
return sum(count(done | {v}) for v in names if v not in done and preds[v] <= done)
print("topological orders of the release plan:", count(frozenset()))
def dfs_order(adj):
seen, order = set(), []
def visit(u):
seen.add(u)
for v in adj[u]:
if v not in seen:
visit(v)
order.append(u)
for u in adj:
if u not in seen:
visit(u)
return order[::-1]
rng = random.Random(3)
for trial in range(500):
n = rng.randint(1, 30)
perm = list(range(n)); rng.shuffle(perm) # hidden order; edges go forward in it
g = {u: [] for u in range(n)}
for i in range(n):
for j in range(i + 1, n):
if rng.random() < 0.15:
g[perm[i]].append(perm[j])
order = dfs_order(g)
pos = {v: i for i, v in enumerate(order)}
assert sorted(order) == list(range(n)) and all(pos[u] < pos[v] for u in g for v in g[u])
print("DFS produced a valid topological order for 500 random DAGs")topological orders of the release plan: 9
DFS produced a valid topological order for 500 random DAGs
The release plan has 7 tasks, so orders in all, but only 9 of them are valid schedules: the dependencies force most of the order. DFS found one of the nine. The practice problem Course Schedule Order asks for a topological order of courses and prerequisites; the DSA course solves it by example in Topological Sort.
In C++
The C++ version records finishing order in a vector and reverses it at the end, which is equivalent to inserting at the front. It returns an empty vector on a back edge.
#include <algorithm>
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
std::vector<int> topo_sort(const std::vector<std::vector<int>>& adj) {
const int n = static_cast<int>(adj.size());
std::vector<int> color(n, 0), order; // 0 white, 1 gray, 2 black
bool cyclic = false;
std::function<void(int)> visit = [&](int u) {
color[u] = 1;
for (int v : adj[u]) {
if (color[v] == 1) cyclic = true;
else if (color[v] == 0) visit(v);
}
color[u] = 2;
order.push_back(u);
};
for (int u = 0; u < n; ++u)
if (color[u] == 0) visit(u);
if (cyclic) return {};
std::reverse(order.begin(), order.end());
return order;
}
int main() {
const std::string names = "ABCDEFG";
std::vector<std::vector<int>> plan = {{1, 2}, {3}, {3, 4}, {5}, {5, 6}, {}, {5}};
std::printf("release plan:");
for (int v : topo_sort(plan)) std::printf(" %c", names[v]);
std::printf("\n");
std::vector<std::vector<int>> loop = {{1}, {2}, {0}};
std::printf("three-cycle: %s\n", topo_sort(loop).empty() ? "cycle, no order" : "ordered");
}release plan: A C E G B D F
three-cycle: cycle, no order
Test yourself
DFS on a DAG gives finishing times , , , . What is the topological order?
- It cannot be determined
Why can't DFS find gray when it explores an edge of a DAG?
- Because gray vertices have no outgoing edges
- Because a gray is an ancestor of , which would make a back edge and close a cycle
- Because DFS paints every vertex black first
- It can; it is a forward edge
What is the running time of the DFS-based topological sort?
- because it sorts by finishing time
- : one DFS plus a constant-time insertion per vertex