Topological sort
A topological sort orders the nodes of a directed acyclic graph so every edge goes from earlier to later. If the graph has a cycle, no such order exists.
Detailed Explanation
Build systems, course prerequisites, and compilation units are DAGs: you cannot take B before A if A is required for B. A topological order is a sequence that respects every constraint. There may be many legal orders. There is none if a cycle exists.
Kahn's algorithm is the BFS form. Compute indegree of every node. Enqueue all nodes with indegree 0. While the queue is not empty, pop a node, append it to the order, and decrement indegree of its neighbours. A neighbour whose indegree hits 0 is ready. If the order's length is less than n, a cycle remains.
DFS is the other form. Run DFS and append a node after its descendants (post-order). Reverse that list, or push onto a stack and pop. Cycle detection needs the three-colour method; do not reverse a post-order if you skipped that check.
You reach for topological sort when work has prerequisites. You reach for a shortest path on a DAG by relaxing edges in topological order (linear time, handles negative weights). You reach for Dijkstra when the graph may have cycles and non-negative weights.
The cost of treating an arbitrary directed graph as a DAG is a silent partial order. Always compare the result size to n. The cost of adding both (u,v) and (v,u) is a cycle of two. Parallel courses (nodes with indegree 0 at the same time) can be processed in any order; if you need a unique order, the problem will say so (often lexicographically smallest: use a PriorityQueue instead of a deque).
Implementation in Java: adjacency List<List<Integer>>, int[] indegree, ArrayDeque<Integer>. Do not use recursion on a 10^5-node line without an explicit stack.
Code Examples
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Kahn {
static List<Integer> order(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) {
g.add(new ArrayList<>());
}
int[] indeg = new int[n];
for (int[] e : edges) {
g.get(e[0]).add(e[1]);
indeg[e[1]]++;
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
if (indeg[i] == 0) {
q.add(i);
}
}
List<Integer> out = new ArrayList<>();
while (!q.isEmpty()) {
int u = q.removeFirst();
out.add(u);
for (int v : g.get(u)) {
if (--indeg[v] == 0) {
q.addLast(v);
}
}
}
return out.size() == n ? out : List.of();
}
public static void main(String[] args) {
System.out.println(order(4, new int[][] {{0, 1}, {0, 2}, {1, 3}, {2, 3}}));
// prints: [0, 1, 2, 3] or [0, 2, 1, 3]
}
}Common Gotchas
A result shorter than `n` means a cycle
do not return a partial order as if it were valid.
DFS post-order without cycle colours can "sort" a cyclic graph
detect cycles first.
Many orders can be legal
do not hard-code one sequence in tests unless you sort the ready set.
Isolated nodes still belong in the order
they start with indegree 0.