forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
53 lines (45 loc) · 1.18 KB
/
main.go
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
// ex5.10 sorts courses topologically based on hard-coded dependencies.
package main
import (
"fmt"
)
// prereqs maps computer science courses to their prerequisites.
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([]string)
visitAll = func(items []string) {
for _, v := range items {
if !seen[v] {
seen[v] = true
visitAll(m[v])
order = append(order, v)
}
}
}
for k := range m {
visitAll([]string{k})
}
return order
}