Lesson contents

Prerequisites and topological ordering

A topological order puts every prerequisite before the task that needs it. Start with tasks that have no unfinished prerequisites.

Simple example

Tasks 1 and 2 must both finish before 3. Take ready tasks in ascending order and print one valid schedule.

Start1→3 2→3
Result1 2 3
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
        var offsets = Array(0, 1, 2, 2)
        var edges = Array(2, 2)
        var incoming = Array(0, 0, 2)
        var done = 0
        scala.util.control.Breaks.breakable { while (done < 3) {
            var task = 0
            while ((task < 3) && (incoming(task) != 0)) {
                task += 1
            }
            if (task == 3) {
                scala.util.control.Breaks.break()
            }
            println(task + 1)
            incoming(task) = -1
            var i = offsets(task)
            while (i < offsets(task + 1)) {
                incoming(edges(i)) -= 1
                i += 1
            }
            done += 1
        } }
  }
}
Output
1
2
3
Advertisements

Everyday examples

Prepare an order

Picking and printing the label can happen separately. Sealing needs both. Can sealing be the first task?

StartA→C B→C
ResultA B C

Finish A and B in either order. Only then does C have zero remaining prerequisites.

Schedule a room opening

Painting must finish before signs go up, and signs must be up before opening. Which task is last?

StartP→S→O
ResultO

Every arrow points to a later task. Opening comes after both painting and signage.

Spot a circular requirement

Course A requires B, and B requires A. Which course is ready first?

StartA→B B→A
Result∅

Neither has zero prerequisites. Report the cycle so the schedule can be corrected.

Cost and limits

Several valid orders may exist. If unfinished tasks remain when no task is ready, the dependency graph contains a directed cycle.