Problem Solving with Go course

GraphsTopological Sort

Problem Solving with Go

Display

Theme

Graphs · Test exercise

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.

  1. 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.
  2. 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.
main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// Rule says that Before must be done before After.
type Rule struct {
	Before, After string
}

// order returns every step named in the rules, in an order that keeps every rule.
// When the rules go round in a circle, there is no such order and it returns an error.
func order(rules []Rule) ([]string, error) {
	// TODO: count how many earlier steps each step waits for, start with those at 0
	return nil, nil
}

// layers groups the steps into rounds: the first round holds the steps with no rule
// before them, and every later round the steps whose earlier steps are all in previous
// rounds. Each round is sorted A to Z. A circle of rules is an error.
func layers(rules []Rule) ([][]string, error) {
	// TODO
	return nil, nil
}

func main() {
	var rules []Rule
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		before, after, ok := strings.Cut(scanner.Text(), "->")
		if !ok {
			continue
		}
		rules = append(rules, Rule{strings.TrimSpace(before), strings.TrimSpace(after)})
	}
	steps, err := order(rules)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("one way to build it:", strings.Join(steps, ", "))
	rounds, _ := layers(rules)
	for i, round := range rounds {
		fmt.Printf("round %d: %s\n", i+1, strings.Join(round, ", "))
	}
}
Go runtime not loaded yet

10 lines · 170 B of the 1 MB limit. Submit always uses the lesson's own input.