Topological Sort
"The frame goes up after the foundation. The walls need the wiring and the windows. Paint comes last." Rules like these form a directed graph: an edge from a to b means a must come before b. Putting all the steps in an order that keeps every rule is called a topological sort.
Start with what's free
Count, for every step, how many earlier steps it is still waiting for. Steps waiting for nothing can go now. Take one, and every step that was waiting for it waits for one fewer; any that reach zero become free too. This is Kahn's algorithm:
for len(ready) > 0 {
step := ready[0]
ready = ready[1:]
out = append(out, step)
for _, after := range next[step] {
waiting[after]--
if waiting[after] == 0 {
ready = append(ready, after)
}
}
}
Every step and every rule is handled once: O(V + E).
Circles
If the rules say a before b and b before a, no order can keep both. Kahn's algorithm notices on its own: the steps in the circle never reach zero, so the loop ends before every step is placed. Compare the number of placed steps with the number of steps, and report an error when some are left.
More than one right answer
Usually several orders keep every rule. When the drains and the frame both become free, either can go first. Puzzles that want one exact answer say how to choose, for example "take the free step that appears first in the input". Without such a rule, any order that keeps every rule is correct, and that's how this lesson's tests check order.
Rounds
A useful variant takes the free steps all at once: everything free now is round 1; everything that becomes free once round 1 is done is round 2; and so on. With enough helpers, each round can happen in parallel, so the number of rounds is how many turns the whole job takes.
Task
This lesson's input lists the rules for building a shed, one before -> after per line.
- Complete
order(rules []Rule) ([]string, error): every step named in the rules, in an order that keeps every rule. Return an error when the rules go round in a circle. - Complete
layers(rules []Rule) ([][]string, error): the steps in rounds as described above, each round sorted A to Z. Return an error for a circle too.