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
// @Title: 课程表 II (Course Schedule II)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 28 ms
// @Memory: 6.8 MB
func findOrder(numCourses int, prerequisites [][]int) []int {
	next := make([][]int, numCourses)
	for _, pair := range prerequisites {
		next[pair[1]] = append(next[pair[1]], pair[0])
	}

	pres := make([]int, len(next))
	for _, k := range next {
		for _, v := range k {
			pres[v]++
		}
	}

	var i, j int
	n := numCourses
	ret := make([]int, n)
	for i = 0; i < n; i++ {
		for j = 0; j < n; j++ {
			if pres[j] == 0 {
				break
			}
		}

		// 出现环路
		if j >= numCourses {
			return nil
		}

		pres[j] = -1

		for _, c := range next[j] {
			pres[c]--
		}
		ret[i] = j
	}
	return ret
}