leetcode
建立前序后序邻接表,找到入度为零的节点,然后维护邻接表。
最后路径长度等于课程总数则表示可以学完所有课程。
时间复杂度:O(n + m)
空间复杂度:O(n + m)
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
| func findOrder(numCourses int, prerequisites [][]int) []int { result := []int{} pre := make(map[int][]int) post := make(map[int][]int)
for _, req := range prerequisites { x := req[0] y := req[1] pre[x] = append(pre[x], y) post[y] = append(post[y], x) }
queue := []int{}
for i := 0; i < numCourses; i++ { if _, ok := pre[i]; !ok { queue = append(queue, i) } }
for len(queue) > 0 { cur := queue[0] result = append(result, cur) queue = queue[1:] for _, p := range post[cur] { for i, q := range pre[p] { if q == cur { pre[p] = append(pre[p][:i], pre[p][i+1:]...) if len(pre[p]) == 0 { queue = append(queue, p) } break } } }
}
if len(result) != numCourses { return []int{} }
return result }
|