-
Notifications
You must be signed in to change notification settings - Fork 0
/
0210-course-schedule-ii.go
41 lines (37 loc) · 1015 Bytes
/
0210-course-schedule-ii.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
const CRS = 0
const PRE = 1
func findOrder(numCourses int, prerequisites [][]int) []int {
prereq := make([][]int, 0)
for i := 0; i < numCourses; i++ {
prereq = append(prereq, make([]int, 0))
}
for _, edge := range prerequisites {
prereq[edge[CRS]] = append(prereq[edge[CRS]], edge[PRE])
}
output := make([]int, 0)
visit, cycle := make([]bool, numCourses), make([]bool, numCourses)
var dfs func(int) bool
dfs = func(crs int) bool {
if cycle[crs] {
return false
} else if visit[crs] {
return true
}
cycle[crs] = true
for _, pre := range prereq[crs] {
if !dfs(pre) {
return false
}
}
cycle[crs] = false
visit[crs] = true
output = append(output, crs)
return true
}
for c := 0; c < numCourses; c++ {
if dfs(c) == false {
return []int{}
}
}
return output
}