Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created February 12, 2020 01:39
Show Gist options
  • Save HauptJ/dd7be4741c0e055042750f289608b7f7 to your computer and use it in GitHub Desktop.
Save HauptJ/dd7be4741c0e055042750f289608b7f7 to your computer and use it in GitHub Desktop.
func canFinish(numCourses int, prerequisites [][]int) bool {
next := Next(numCourses, prerequisites)
pres := Pres(next)
return check(next, pres, numCourses)
}
func Next(n int, prereq [][]int) [][]int {
next := make([][]int,n)
for _, pair := range prereq {
next[pair[1]] = append(next[pair[1]], pair[0])
}
return next
}
func Pres(next [][]int) []int {
pres := make([]int, len(next))
for _, neighbors := range next {
for _, n := range neighbors {
pres[n]++
}
}
return pres
}
func check(next [][]int, pres []int, numCourses int) bool {
var i int
var j int
for i = 0; i < numCourses; i++ {
for j = 0; j < numCourses; j++ {
if pres[j] == 0 {
break
}
}
if j >= numCourses {
return false
}
pres[j] = -1
for _, c := range next[j] {
pres[c]--
}
}
return true
}
@HauptJ
Copy link
Author

HauptJ commented Feb 12, 2020

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment