Advanced graphs and trees · 10 / 15 Exercise Hard

Topological order

Objective

If some tasks depend on others, a topological order places them so that each task appears after the ones it needs. It only exists if there are no cycles. Kahn’s algorithm always takes a task with no pending dependencies.

Instructions

  • The first line has n m (tasks, from 0 to n-1, and dependencies); then m lines a b, meaning that task a goes before b.
  • Show a valid order; if there are several, the lexicographically smallest (always take the smallest available task, with a priority queue). If there is a cycle, show There is a cycle.
Input
4 4
0 1
0 2
1 3
2 3
Output
0 1 2 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise