- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcourse_schedule.go
50 lines (35 loc) · 890 Bytes
/
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
package main
funccanFinish(numCoursesint, prerequisites [][]int) bool {
graph:=make([][]int, numCourses)
fori:=0; i<numCourses; i++ {
graph[i] =make([]int, 0)
}
for_, pre:=rangeprerequisites {
x:=pre[0]
y:=pre[1]
graph[x] =append(graph[x], y)
}
visited:=make([]int, numCourses)
fori:=0; i<numCourses; i++ {
ifhasCycle(graph, visited, i) {
returnfalse// Cycle detected
}
}
returntrue
}
funchasCycle(graph [][]int, visited []int, nodeint) bool {
ifvisited[node] ==1 {
returntrue// Cycle detected
}
ifvisited[node] ==-1 {
returnfalse// Already visited and no cycle
}
visited[node] =1// Mark node as visited
for_, neighbor:=rangegraph[node] {
ifhasCycle(graph, visited, neighbor) {
returntrue// Cycle detected
}
}
visited[node] =-1// Mark node as visited and no cycle
returnfalse
}