Created
February 12, 2020 01:39
-
-
Save HauptJ/dd7be4741c0e055042750f289608b7f7 to your computer and use it in GitHub Desktop.
207. Course Schedule - https://leetcode.com/problems/course-schedule/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Author
HauptJ
commented
Feb 12, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment