Graph Algorithms

Topological Sort With Kahn's Algorithm

A0 inB1 inC1 inD2 inE1 inF1 inG2 inH2 in
In the queue

Empty.

Order so far

Nothing yet.

  • Not reached
  • Waiting
  • Current
  • Finished
1/21

Count the incoming edges of every node: A=0 B=1 C=1 D=2 E=1 F=1 G=2 H=2.

Settings

Graph

Topological Sort

  1. 1count incoming edges per node
  2. 2queue = nodes with zero incoming
  3. 3while queue:
  4. 4 node = queue.shift()
  5. 5 output.push(node)
  6. 6 for each neighbour:
  7. 7 incoming[neighbour] -= 1
  8. 8 if incoming[neighbour] == 0:
  9. 9 queue.push(neighbour)

What Each One Answers

AlgorithmWhat it answersTimeNeeds
Breadth-FirstFewest hops from the startO(V + E)A queue
Depth-FirstReachability, one branch at a timeO(V + E)A stack
Cycle DetectionWhether there is a cycle, and whereO(V + E)Node colours
Topological SortA valid order to do the work inO(V + E)No cycles
DijkstraCheapest path by edge weightO(E log V)Non-negative weights

Scroll the table sideways for the rest of the columns.

V is the number of nodes and E the number of edges. On the graph with a cycle, topological sort gets stuck, because a cycle leaves no valid order.