40 lines
795 B
Go
40 lines
795 B
Go
package top100liked
|
|
|
|
// https://leetcode.cn/problems/course-schedule/?envType=study-plan-v2&envId=top-100-liked
|
|
|
|
import "slices"
|
|
|
|
func canFinish(numCourses int, prerequisites [][]int) bool {
|
|
adjacencyList := make([][]int, numCourses)
|
|
for _, prerequisit := range prerequisites {
|
|
from, to := prerequisit[1], prerequisit[0]
|
|
adjacencyList[from] = append(adjacencyList[from], to)
|
|
}
|
|
|
|
state := make([]int, numCourses)
|
|
|
|
var hasCycle func(int) bool
|
|
hasCycle = func(node int) bool {
|
|
if state[node] == 1 {
|
|
return true
|
|
}
|
|
if state[node] == 2 {
|
|
return false
|
|
}
|
|
state[node] = 1
|
|
if slices.ContainsFunc(adjacencyList[node], hasCycle) {
|
|
return true
|
|
}
|
|
state[node] = 2
|
|
return false
|
|
}
|
|
|
|
for i := 0; i < numCourses; i++ {
|
|
if hasCycle(i) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|