Created
April 9, 2023 17:33
-
-
Save saldisobi/bffa6b35f3538615a24735a4d49af9e4 to your computer and use it in GitHub Desktop.
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
class Solution { | |
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean { | |
val indegree = IntArray(numCourses) | |
prerequisites.forEach{preArr-> | |
val dependentCourse = preArr[0] | |
indegree[dependentCourse]++ | |
} | |
val queue = LinkedList<Int>() | |
indegree.forEachIndexed{index, dependencies-> | |
if(dependencies == 0){ | |
queue.add(index) | |
} | |
} | |
if(queue.isEmpty()){ | |
return false | |
} | |
var index = 0 | |
while(!queue.isEmpty()){ | |
val courseDone = queue.remove() | |
index++ | |
prerequisites.forEach{preArr-> | |
if(courseDone == preArr[1]){ | |
val dependentCourse = preArr[0] | |
indegree[dependentCourse]-- | |
if(indegree[dependentCourse] == 0){ | |
queue.add(dependentCourse) | |
} | |
} | |
} | |
} | |
return index == numCourses | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment