-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcourse_schedule_ii.go
More file actions
46 lines (36 loc) · 836 Bytes
/
course_schedule_ii.go
File metadata and controls
46 lines (36 loc) · 836 Bytes
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
package leetcode
func findOrder(numCourses int, prerequisites [][]int) []int {
indegree := make([]int, numCourses)
adj_list := make(map[int][]int)
for _, el := range prerequisites {
course, pre := el[0], el[1]
indegree[course] += 1
if _, ok := adj_list[course]; ok == false {
adj_list[course] = make([]int, 0, 1)
}
adj_list[pre] = append(adj_list[pre], course)
}
stack := make([]int, 0)
res := make([]int, 0)
for i, el := range indegree {
if el == 0 {
stack = append(stack, i)
}
}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
for _, el := range adj_list[node] {
indegree[el] -= 1
if indegree[el] == 0 {
stack = append(stack, el)
}
}
res = append(res, node)
}
if len(res) == numCourses {
return res
} else {
return make([]int, 0)
}
}