目录
习题答案,个人理解,欢迎交流指正
5.11
package main
import (
"fmt"
"sort"
)
var dict = map[string][]string{
"algorithms": {"data structures"},
"calculus": {"linear algebra"},
"linear algebra": {"calculus"},
"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() {
list, ok := toposort(dict)
if !ok {
fmt.Println("存在环")
return
}
for i, s := range list {
fmt.Printf("%d\t%s\n", i+1, s)
}
}
func toposort(dict map[string][]string) ([]string, bool) {
var list []string
seen := make(map[string]bool)
wait := make(map[string]bool)
var visitAll func(items []string) bool
visitAll = func(items []string) bool {
for _, item := range items {
if !seen[item] {
seen[item] = true
wait[item] = true
if !visitAll(dict[item]) {
return false
}
list = append(list, item)
wait[item] = false
} else if wait[item] {
return false
}
}
return true
}
var keys []string
for key := range dict {
keys = append(keys, key)
}
sort.Strings(keys)
if !visitAll(keys) {
return nil, false
}
return list, true
}
5.13
package main
import (
"fmt"
"io/ioutil&