This commit is contained in:
2026-07-02 13:48:46 +08:00
parent e2f0b5c11a
commit 8f176c1836
5 changed files with 339 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
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
}