-
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
func canFinish(numCourses int, prerequisites [][]int) bool {
graph := make([][]int, numCourses)
for i := 0; i < numCourses; i++ {
graph[i] = make([]int, 0)
}
for _, pre := range prerequisites {
x := pre[0]
y := pre[1]
graph[x] = append(graph[x], y)
}
visited := make([]int, numCourses)
for i := 0; i < numCourses; i++ {
if hasCycle(graph, visited, i) {
return false // Cycle detected
}
}
return true
}
func hasCycle(graph [][]int, visited []int, node int) bool {
if visited[node] == 1 {
return true // Cycle detected
}
if visited[node] == -1 {
return false // Already visited and no cycle
}
visited[node] = 1 // Mark node as visited
for _, neighbor := range graph[node] {
if hasCycle(graph, visited, neighbor) {
return true // Cycle detected
}
}
visited[node] = -1 // Mark node as visited and no cycle
return false
}