Chapter 14 · Simulation

Course Prerequisite Planner

← Chapter 14

u → v: take u before v

kahn(adj)

    indeg[]
    q
    result
    plan

    Course Prerequisite Planner

    Courses are vertices and prerequisites are directed edges: an edge u → v says that u must be taken before v. A valid course plan is a topological order of this graph, computed here step by step with Kahn's algorithm.

    How to use it

    • Add a course by name, then pick the Before and After courses and press Add Prerequisite (Remove deletes the edge).
    • Example loads 6 courses with 7 prerequisites; With Cycle loads the example plus an edge that closes a cycle; Clear deletes everything.
    • Step through with ⏮ ◀ ▶, or press Play to run them all. The highlighted line in kahn(adj) is the one being executed.
    • On each vertex, in shows the in-degree and S the semester in which the course can be taken.

    What the rows show

    • indeg[]: each course's in-degree (the number of unmet prerequisites).
    • q: the queue of courses with in-degree 0, which can be taken right away.
    • result: the topological order produced so far.
    • plan: the courses grouped into semesters by their longest prerequisite chains.

    Kahn's algorithm

    Compute every in-degree and enqueue the courses with in-degree 0. Then, at each step, remove a course from the queue, append it to the result, and decrement the in-degree of each of its successors; any that reach 0 join the queue. If the result ends up with fewer courses than the graph, the rest lie on a cycle or wait for a course that does, and no valid plan exists. The algorithm runs in O(n + m) time.