Kahn's algorithm maintains each remaining vertex's indegree, the number of its unfinished incoming directed edges, and a FIFO queue of ready vertices. Initialize the counts by scanning all directed edges and enqueue every vertex of indegree zero. Repeatedly dequeue a vertex , append it to the output, and decrement the count of each destination in 's adjacency list. Enqueue exactly when its count becomes zero. When the FIFO queue empties, accept the output if it contains all vertices; otherwise report a directed cycle. [ref]
Figure 1.
Computed ready-queue trace and the obstruction caused by a reverse dependency
. Details.
In the displayed run, initialize the FIFO queue as and visit 's destinations in the order . Removing makes ready but leaves waiting for . Removing then makes ready. Publication becomes ready only after both and are removed. The output is ; choosing ready vertices differently can produce the other topological orders. For the modified directed graph with , the same procedure emits and then stops with still waiting on each other.
The invariant is that each stored indegree counts incoming directed edges from unprocessed vertices. A ready vertex therefore has every prerequisite already in the output. If the FIFO queue empties with vertices left, every remaining vertex has a predecessor in the remaining directed graph; the predecessor argument gives a directed cycle. The unprocessed vertices can also include tasks blocked downstream of a directed cycle, so the leftover list alone is not a list of exactly the cyclic vertices.
With adjacency lists, constant-time array access and counter updates, and constant-time FIFO queue operations, the time complexity is in Big O notation. Initialization scans all vertices and directed edges; each vertex is then enqueued at most once and each outgoing directed edge processed at most once. Counts, ready FIFO queue, and output need storage beyond the adjacency lists. Shifting an array on every dequeue invalidates this bound. [ref] [ref]
The name refers to A. B. Kahn's 1962 paper "Topological sorting of large networks", published in Communications of the ACM, volume 5, issue 11, pages 558–562. Its abstract motivates topological sorting through network analysis and project planning. [ref]

Articles by others on the same topic (0)

There are currently no matching articles.