AlgoFrames

Topological order

Warm-up · Trace the algorithm · about 4 min

Kahn's algorithm runs on this graph. It starts with the in-degree-0 nodes in number order and handles each node's edges in the order listed. Drag the nodes into the order Kahn's algorithm outputs them.

Example 1

Input:

{"edges":[[5,2],[0,2],[0,3],[2,4],[3,4],[4,1],[3,1]]}

Output:

[0,5,3,2,4,1]

Labels show in-degrees. 0 and 5 start in the queue.

Constraints

  • The queue starts with 0, then 5.
  • A node joins the queue when its in-degree reaches 0.

Learn the idea first: Topological sort: Kahn's algorithm and DFS finishing order, a visual lesson.

More Topological sort: Kahn's algorithm and DFS finishing order problems