Medium Graphs

Course Schedule (Topological Sort)

Given a set of N courses and the prerequisites between them, works out an order in which every course can be taken — the topological sort behind build systems, package installers and task pipelines. Receives the prerequisites as a square adjacency matrix, where a nonzero value at row i, column j means course i must be taken before course j (0 means no dependency). Applies Kahn's algorithm: it counts how many prerequisites each course is still waiting on (its indegree), queues every course that has none, and then repeatedly takes a course out of the queue, appends it to the order and decrements the indegree of every course that depended on it, queueing any that drop to zero. Returns a valid order of all N courses, or an empty list when a cycle of mutual prerequisites makes the schedule impossible.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References