DAGs, Topological Sort & Strong Connectivity
Ordering dependencies, finding cycles and condensing a directed graph.
A build system, a spreadsheet and a package manager all answer the same question thousands of times a day: given rules of the form "X must come before Y", find an order that obeys every rule, or prove that none exists. One linear-time pass does both, and the depth-first search behind it also splits any directed graph into strongly connected pieces arranged in a DAG.
What you’ll learn
- Prove that a directed graph has a topological order if and only if it has no directed cycle.
- Compute a topological order with Kahn's algorithm or with DFS finishing times in , detect cycles with each, and find the lexicographically smallest order with a min-heap.
- Define strongly connected components, prove that the condensation is a DAG, and outline Kosaraju's and Tarjan's linear-time algorithms.
- Compute longest paths and path counts in a DAG by dynamic programming in topological order.
- Recognize prerequisite, build-order and scheduling problems as DAG problems, and avoid their classic bugs.
Orders that respect every arrow
In a directed graph an edge often means " must happen before ": a course before the course that requires it, a source file before the files that import it, a spreadsheet cell before the formulas that read it. A topological order lists all vertices so that every edge points forward: whenever is an edge, comes before .
Such an order does not always exist. If requires and requires , no schedule works. The obstacle is always a directed cycle, and the graphs without one have their own name: directed acyclic graphs, or DAGs.
A cycle blocks every order. Suppose is a cycle and is the position of in a topological order. Every edge points forward, so
Every nonempty DAG has a source, a vertex with no incoming edge. Otherwise, start anywhere and keep stepping backward along incoming edges. After steps some vertex has repeated, and the walk between the two visits, read forward, is a directed cycle:
Peel off a source. Put a source first and delete it. Deleting a vertex cannot create a cycle, so what remains is a DAG on vertices; by induction it has a topological order, and followed by that order is a topological order of the whole graph:
Think first How many topological orders does a DAG on vertices with no edges have? And a single path ?
and exactly . Other DAGs fall in between, and counting their orders exactly is -complete (Brightwell & Winkler, 1991), even though finding one order takes linear time. Whenever a problem wants one particular order, it must say which, for example the lexicographically smallest.
Kahn’s algorithm: peel off the sources
The proof is an algorithm. Keep a counter of the edges into not yet removed, and a queue of the vertices whose counter is : they are ready. Repeatedly take a ready vertex, output it, and remove its outgoing edges by decrementing its out-neighbors' counters; a vertex joins the queue the moment its counter reaches . This is Kahn's algorithm (1962).
from collections import deque
def topo_order(n, edges):
"""Kahn's algorithm: a topological order of 0..n-1, or None if there is a cycle."""
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
queue = deque(v for v in range(n) if indeg[v] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: # v's last prerequisite is done
queue.append(v)
return order if len(order) == n else None # leftovers: a cycle blocks themEach vertex enters and leaves the queue once and each edge is examined once: time and memory with adjacency lists. Vertices that appear in no edge start ready and are output too.
Cycle detection comes free. If the queue empties while vertices remain, those leftovers can never become ready: each one still has an incoming edge from another leftover. Walking backward along such edges stays among the leftovers, so it must repeat a vertex and close a cycle. Conversely, the vertices of a cycle block each other forever. So Kahn's algorithm outputs all vertices if and only if the graph is a DAG.
Kahn's algorithm runs on a directed graph and stops with three vertices never output. Which statement must be true?
- Each of the three vertices lies on a directed cycle
- The leftovers contain a directed cycle, and every leftover vertex lies on a cycle or can be reached from one
- The graph is a DAG, but the algorithm started from the wrong vertex
- The graph has exactly one directed cycle
Show the answer
B. The leftovers contain a directed cycle, and every leftover vertex lies on a cycle or can be reached from one
Every leftover vertex keeps an incoming edge from another leftover, so walking backward from any of them stays among the leftovers and closes a cycle: each leftover lies on a cycle or downstream of one. In the graph , , , , Kahn's algorithm outputs and leaves , but only and lie on the cycle.
Depth-first search: reverse finishing order
The second classic method needs no counters. Run a depth-first search from every unvisited vertex and record each vertex when it finishes, that is, once everything reachable from it has been explored. Then output the vertices in reverse order of finishing time . Color the vertices white (unseen), gray (on the recursion stack) and black (finished).
Consider the moment DFS scans the edge ; then is gray. If is white, becomes a descendant of and finishes first:
If is black, it has already finished, while is still running:
If is gray, it is an ancestor of on the recursion stack, so the tree path from to plus the edge is a directed cycle. In a DAG this case cannot happen, which proves the first claim and half of the second:
Every cycle produces a back edge. Let be the first vertex of a cycle that DFS discovers. At that moment the rest of the cycle is white and reachable from through white vertices, so all of it becomes a descendant of , including the vertex just before on the cycle. When DFS scans , the search of has not finished:
import sys
def topo_dfs(n, adj):
"""Reverse postorder of a depth-first search; None if a back edge closes a cycle."""
sys.setrecursionlimit(10_000 + 2 * n)
color = [0] * n # 0 white (unseen), 1 gray (on the stack), 2 black (finished)
post = []
def visit(u):
color[u] = 1
for v in adj[u]:
if color[v] == 1 or (color[v] == 0 and not visit(v)):
return False # a back edge u -> v closes a cycle
color[u] = 2
post.append(u) # u finishes after everything it can reach
return True
for s in range(n):
if color[s] == 0 and not visit(s):
return None
return post[::-1]. Looping over every start vertex covers graphs that are not reachable from one place. Python's default recursion limit is 1,000 frames, so the code raises it; for very deep inputs, such as a chain of prerequisites, prefer Kahn's algorithm or an explicit stack.
Which order? The two methods usually output different orders, both valid. When a problem wants a particular one, say the lexicographically smallest, choose it explicitly: in Kahn's algorithm always take the smallest ready vertex, with a min-heap instead of a queue, for time. The greedy choice is safe because the vertex placed next must be ready, and every ready vertex can be extended to a full order. DFS with sorted neighbors does not do this: with vertices and the single edge , the smallest order is , but reverse finishing order from a DFS that starts at gives .
#include <cstdio>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
int main() {
int n, m;
if (scanf("%d %d", &n, &m) != 2) return 0;
vector<vector<int>> adj(n + 1);
vector<int> indeg(n + 1, 0);
for (int i = 0; i < m; i++) {
int u, v;
if (scanf("%d %d", &u, &v) != 2) return 0;
adj[u].push_back(v);
indeg[v]++;
}
priority_queue<int, vector<int>, greater<int>> ready; // min-heap of available vertices
for (int v = 1; v <= n; v++)
if (indeg[v] == 0) ready.push(v);
vector<int> order;
while (!ready.empty()) {
int u = ready.top();
ready.pop();
order.push_back(u);
for (int v : adj[u])
if (--indeg[v] == 0) ready.push(v);
}
if ((int)order.size() < n) { puts("IMPOSSIBLE"); return 0; }
for (int i = 0; i < n; i++) printf("%d%c", order[i], i + 1 < n ? ' ' : '\n');
}Contest style: vertices , then the edges. A priority_queue with greater<int> is a min-heap; with a plain queue the same loop is Kahn's algorithm in .
Strongly connected components and the condensation
A graph with cycles still has structure. Call and strongly connected if each can reach the other. The relation is reflexive, symmetric and transitive, so it splits the vertices into classes, the strongly connected components (SCCs). Inside a component every vertex reaches every other; between two components, reachability goes one way at most.
So every directed graph is a DAG of strongly connected pieces: a plain DAG when every piece is one vertex, strongly connected when there is a single piece. Two classic linear-time algorithms find the pieces, both built on DFS:
| Algorithm | How it works | Order of the components found |
|---|---|---|
| Kosaraju–Sharir (Kosaraju 1978, unpublished; Sharir 1981) | DFS on records finishing times. A second DFS runs on the reversed graph , always starting from the unvisited vertex that finished last; each search tree of this pass is one SCC. | Topological order of the condensation (sources first) |
| Tarjan (1972) | One DFS keeps a stack of vertices and a low-link value : the smallest discovery time of a vertex still on the stack that 's subtree can reach with one extra edge. When , is the first vertex of its component, which is popped off the stack. | Reverse topological order (sinks first) |
Think first Why does Kosaraju's second pass run on the reversed graph? What would a search in itself, started from the vertex that finished last, collect?
The last finisher lies in a source component of the condensation, and from a source component much of the graph is usually reachable: a search in would sweep up every component downstream of it. Reversing every edge turns that source component into a sink, so a search there in cannot leave it and collects exactly one SCC. With that component removed, the latest remaining finisher again lies in a sink of what is left of , and so on. The Optimal lesson proves this lemma about finishing times.
Applications are everywhere: a cycle in a "wait-for" graph of processes is a deadlock; compilers find loops as SCCs of a program's control-flow graph; reachability and model-checking tools collapse each SCC to one node before doing anything else; and the 2-SAT algorithm decides a Boolean formula by computing the SCCs of its implication graph.
Dynamic programming on a DAG
A topological order is exactly the order a dynamic program needs: by the time vertex is processed, every edge into has been considered. One pass over the vertices computes, from a source , the longest or shortest path to every vertex (negative weights are fine), the number of distinct paths, or the earliest time each task of a project can start.
def dag_paths(n, edges, order, s):
"""Longest path length and number of paths from s to every vertex of a DAG."""
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
best = [float('-inf')] * n
ways = [0] * n
best[s], ways[s] = 0, 1
for u in order: # every edge into v is relaxed before v is used
for v, w in adj[u]:
best[v] = max(best[v], best[u] + w)
ways[v] += ways[u]
return best, ways given a topological order. Replace max with min for shortest paths. Python integers never overflow, but in C++ path counts outgrow 64 bits quickly, which is why problems ask for them modulo a prime.
Six courses: and have no prerequisites, requires both and , and each require , and requires . You may take any number of courses per semester. What is the minimum number of semesters?
Show the answer
4
The answer is the number of vertices on a longest path. has four, so four semesters are necessary, and taking every course as soon as its prerequisites are done achieves four: , , , . These are the "layers" of Kahn's algorithm when it removes all ready vertices at once.
Recognizing it
Signals. "Prerequisites", "depends on", "must come before", "build order", "is a valid schedule possible?", or any process that only moves forward (a recipe, versions of a file, moves on a grid that only go right or down). "Each can reach the other", "mutually reachable" or "groups that cannot be separated" point to SCCs. Constraints of to vertices and edges call for a linear-time pass.
| Problem (in our words) | Key idea | Time |
|---|---|---|
| Can every course be finished, given the prerequisite pairs? | Kahn's algorithm: feasible if and only if all vertices are output | |
| Recover the letter order of an alien alphabet from a sorted list of words | Compare neighboring words: their first differing letters give an edge; then sort the letters topologically. A word followed by its own proper prefix, or a cycle, means no alphabet fits | for total length and alphabet size |
| Fewest semesters with unlimited courses per semester | Longest path counted in vertices: the number of Kahn layers | |
| The smallest-numbered valid order | Kahn's algorithm with a min-heap | |
| Fewest new edges so that every vertex can reach every other | Compute the SCCs; if the condensation has vertices, sources and sinks, the answer is (Eswaran & Tarjan, 1976) |
Common bugs.
- Reversed arrows: " requires " is the edge .
- Reporting a cycle at any visited vertex instead of at a gray one.
- Forgetting isolated vertices, which appear in no edge but still belong in the order.
- Recursion depth: a chain of prerequisites overflows a default recursion limit or a small C++ stack.
- Using the order before checking that all vertices made it into it.
A build has steps and dependencies "step must run before step ". Output a valid order, or, if the dependencies are circular, report one circular chain of steps. Which technique fits?
- Dijkstra's algorithm from every step that has no dependencies
- Union-find over the dependency pairs, reporting a cycle when two steps already share a set
- DFS with white, gray and black: reverse finishing order, and at an edge into a gray vertex, read the cycle off the recursion stack
- Backtracking over orders of the steps, checking each against the dependencies
Show the answer
C. DFS with white, gray and black: reverse finishing order, and at an edge into a gray vertex, read the cycle off the recursion stack
DFS gives the order in , and when it scans an edge into a gray vertex, the gray vertices from down to on the stack are the cycle to report. Kahn's algorithm also decides feasibility, but it only tells you which vertices are blocked; extracting a cycle from the leftovers takes one more walk.
Key takeaways
- A directed graph has a topological order if and only if it is a DAG. Kahn's algorithm (repeatedly remove a vertex of in-degree 0) and reverse DFS finishing order both find one in .
- Kahn's algorithm exposes a cycle as leftover vertices; DFS exposes one as an edge into a gray vertex, never merely a visited one.
- The lexicographically smallest order comes from Kahn's algorithm with a min-heap, in .
- Strongly connected components partition every directed graph, and the condensation is a DAG; Kosaraju's and Tarjan's algorithms find the components in linear time.
- Dynamic programming in topological order computes longest paths, path counts and schedules in ; on graphs with cycles, the longest simple path is NP-hard.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
DFS runs on a DAG, with discovery times and finishing times . For an edge , which statement always holds?
- and
Show the answer
B.
Whether is white or black when the edge is scanned, it finishes before ; it cannot be gray in a DAG. That is exactly why decreasing finishing time is a topological order.
You need the lexicographically smallest topological order of the vertices . Which method is correct?
- Kahn's algorithm with a min-heap of ready vertices
- DFS visiting neighbors in increasing order, then reversing the finishing order
- Kahn's algorithm with a first-in, first-out queue initialized in increasing order
- Sort the vertices by in-degree, breaking ties by number
Show the answer
A. Kahn's algorithm with a min-heap of ready vertices
Position by position, the next vertex must be ready, and the smallest ready vertex can always be extended to a full order, so taking it is optimal. A min-heap gives .
A DFS cycle check marks vertices as visited and reports a cycle whenever it meets a visited vertex. On which graph does it report a cycle that does not exist?
- ,
- , ,
- , ,
- ,
Show the answer
C. , ,
Whichever of and the search from explores first, it later meets the finished vertex again, through or through . That vertex is black, not gray: the graph is a DAG. Only an edge into a gray vertex proves a cycle.
Count the paths from to in a DAG with vertices and edges, modulo . What is the right approach?
- Enumerate every path with DFS and count those that end at
- BFS from , counting how many times is reached
- Run Dijkstra's algorithm and count shortest paths
- Dynamic programming in topological order: is the sum of over the edges
Show the answer
D. Dynamic programming in topological order: is the sum of over the edges
Every path into arrives through exactly one last edge , so the counts add up, and a topological order makes each final before it is used: in total. The counts themselves can be astronomically large, so they are reduced modulo the prime as they are added.
Go deeper
- Strongly Connected Components: Tarjan & Kosaraju · Two linear-time algorithms, and why they work.
- 2-SAT · Boolean formulas with two-literal clauses, solved through implication graphs.
- Paths in DAGs · Longest paths, critical paths and dynamic programming in topological order.
Further reading
- A. B. Kahn, "Topological sorting of large networks," Communications of the ACM 5(11) (1962), 558–562.
- R. E. Tarjan, "Depth-first search and linear graph algorithms," SIAM Journal on Computing 1(2) (1972), 146–160.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 20.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), §4.2 "Directed Graphs".