- Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathcourse_schedule.go
70 lines (67 loc) · 1.51 KB
/
course_schedule.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package course_schedule
// BFS
funccanFinish(numCoursesint, prerequisites [][]int) bool {
graph:=map[int][]int{}
inDegree:=make([]int, numCourses)
fori:=rangeprerequisites {
graph[prerequisites[i][1]] =append(graph[prerequisites[i][1]], prerequisites[i][0])
inDegree[prerequisites[i][0]]++
}
queue:= []int{}
fori:=rangeinDegree {
ifinDegree[i] ==0 {
queue=append(queue, i)
}
}
forlen(queue) !=0 {
head:=queue[0]
queue=queue[1:]
fori:=rangegraph[head] {
inDegree[graph[head][i]]--
ifinDegree[graph[head][i]] ==0 {
queue=append(queue, graph[head][i])
}
}
}
fori:=rangeinDegree {
ifinDegree[i] !=0 {
returnfalse
}
}
returntrue
}
// DFS
funccanFinishDFS(numCoursesint, prerequisites [][]int) bool {
graph:=map[int][]int{}
fori:=rangeprerequisites {
graph[prerequisites[i][1]] =append(graph[prerequisites[i][1]], prerequisites[i][0])
}
path:=make([]bool, numCourses)
visited:=make([]bool, numCourses)
fori:=0; i<numCourses; i++ {
ifvisited[i] {
continue
}
ifhasCycle(i, graph, path, visited) {
returnfalse
}
}
returntrue
}
funchasCycle(startint, graphmap[int][]int, path []bool, visited []bool) bool {
fori:=rangegraph[start] {
ifvisited[graph[start][i]] {
continue
}
ifpath[graph[start][i]] {
returntrue
}
path[graph[start][i]] =true
ifhasCycle(graph[start][i], graph, path, visited) {
returntrue
}
path[graph[start][i]] =false
}
visited[start] =true
returnfalse
}