How topological sort orders a directed acyclic graph

Short answer: Topological sort orders a directed graph so every edge points forward. Kahn’s algorithm peels vertices of indegree zero and reduces their successors’ indegrees. Depth-first search emits vertices in reverse order of finish time. Both run in Θ(V+E). If Kahn’s queue empties before every vertex is emitted, or if the depth-first search sees a back edge, the graph has a cycle and no order exists.


What the problem actually asks

A schedule, a build, or a spreadsheet needs each job after the jobs it depends on. That is an order of the vertices in which every edge u→v has u before v. Such an order exists exactly when the directed graph has no cycle. A cycle would ask a job to precede itself.

Two constructions produce an order. One repeatedly removes a job that nobody is waiting on. The other finishes a job only after everything reachable from it has finished, then reads those finish times backward. They are the same existence result and different witnesses.


What the algorithm guarantees

On a DAG both algorithms produce a valid topological order and run in Θ(V+E) with an adjacency list. The order is not unique when several sources are available. Kahn’s algorithm can prefer the smallest id among sources and then the order is deterministic. The depth-first order depends on adjacency-list order.

If the graph contains a cycle, Kahn’s algorithm emits fewer than |V| vertices and the unemitted subgraph has minimum indegree at least 1, which is a cycle witness if followed. Depth-first search reports a back edge to a vertex still on the stack. Either test is the decision procedure. A graph with an edge into a finished region is fine. A back edge is not.


The working steps

  1. Kahn: compute every indegree. Enqueue every vertex of indegree 0.
  2. Dequeue u, append u to the order, and decrement the indegree of each successor. A successor whose indegree hits 0 is enqueued.
  3. If the order contains every vertex, it is a topological order. Otherwise the remaining vertices lie on cycles.
  4. Depth-first alternative: run a full depth-first search. On a back edge, reject the graph. Otherwise the reverse of the finish order is a topological order.
  5. The outer loop of that search must start a new tree at every undiscovered vertex, or a source that nothing points from may be missed if it is not the first start.

The order is for a directed acyclic graph. An undirected graph does not have edge direction to respect. A directed graph with a cycle has no answer, and returning a partial Kahn order without saying so omits the jobs that could not be scheduled. Shortest paths in a DAG are a different algorithm that can relax edges in this order in O(V+E).


Approaches that look simpler and fail

Approach Why it fails when a cycle is present and an order is still returned
Sort by vertex id An edge from a larger id to a smaller id points backward. The order has nothing to do with the edges.
Return Kahn’s partial list when the queue dies early The missing vertices are exactly the ones that cannot be ordered. A caller that builds those jobs anyway has ignored a cycle.
Reverse the discovery times instead of the finish times Discovery order is the order trees were entered. An edge to a later tree can point at a vertex discovered earlier. Finish order is the one that works.
Start depth-first search only at vertex 0 Another component, or another source, never finishes and is absent from the order.

Shortest or longest paths in a DAG, after an order exists, are a linear relaxation in that order. Strongly connected components, which collapse the cycles first, belong to Tarjan or Kosaraju. The graph that remains after contracting those components is the DAG this sort can order.


A working example

The Bash script and the Python script Kahn-sort a dag. Edges are 0→2, 1→2, 2→3. Sources start at indegree zero. Both print one valid order, 0 1 2 3.

n=4
adj=("2" "2" "3" "")
indeg=(0 0 0 0)
for ((u=0; u<n; u++)); do
  for v in ${adj[u]}; do indeg[v]=$((indeg[v]+1)); done
done
q=()
for ((i=0; i<n; i++)); do
  if (( indeg[i] == 0 )); then q+=("$i"); fi
done
head=0
order=()
while (( head < ${#q[@]} )); do
  u=${q[head]}; head=$((head+1))
  order+=("$u")
  for v in ${adj[u]}; do
    indeg[v]=$((indeg[v]-1))
    if (( indeg[v] == 0 )); then q+=("$v"); fi
  done
done
echo "${order[*]}"
from collections import deque

n = 4
adj = [[2], [2], [3], []]
indeg = [0, 0, 0, 0]
for u in range(n):
    for v in adj[u]:
        indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
    u = q.popleft()
    order.append(u)
    for v in adj[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            q.append(v)
assert order == [0, 1, 2, 3]
print(*order)

Where it is used

A build system such as Make, a package installer, and a spreadsheet recalculation all need a topological order of a dependency graph. A cycle means the order does not exist and the tool reports it. Depth-first finishing times are one way to produce the order.


When you can drop this algorithm

Drop topological sort when the graph may contain a cycle and the caller has no plan for the rejection. The useful output is then the strongly connected components. Keep either Kahn’s algorithm or reverse finish times when the input is a DAG, or when a cycle must be reported by the same pass.


Why this stays published

We publish this so a search for topological sort returns both the indegree queue and the reverse finish order, plus the cycle test each one carries. Topological sort orders a DAG in linear time by peeling indegree-zero vertices or by reversing depth-first finish times, and a leftover vertex or a back edge means a cycle.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *