1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
package main
import ( "fmt" "sort" )
var prereqs = map[string][]string{ "algorithms": {"data structures"}, "calculus": {"linear algebra"},
"compilers": { "data structures", "formal languages", "computer organization", },
"data structures": {"discrete math"}, "databases": {"data structures"}, "discrete math": {"intro to programming"}, "formal languages": {"discrete math"}, "networks": {"operating systems"}, "operating systems": {"data structures", "computer organization"}, "programming languages": {"data structures", "computer organization"}, }
func main() { for i, course := range topoSort(prereqs) { fmt.Printf("%d:\t%s\n", i+1, course) } }
func topoSort(m map[string][]string) []string { var order []string seen := make(map[string]bool) var visitAll func(items []string)
visitAll = func(items []string) { for _, item := range items { if !seen[item] { seen[item] = true visitAll(m[item]) order = append(order, item) } } }
var keys []string for key := range m { keys = append(keys, key) }
sort.Strings(keys) visitAll(keys) return order }
|