classSolution fun Solution.checkIfPrerequisite( numCourses: Int, prerequisites: Array<IntArray>, queries: Array<IntArray> ): List<Boolean> { val queue = ArrayDeque<Int>() val prerequisiteMap = Array(numCourses) { HashSet<Int>() } val inDegree = IntArray(numCourses) val outDegree = Array<ArrayList<Int>>(numCourses) { ArrayList() } val ans = ArrayList<Boolean>()
for (pair in prerequisites) { inDegree[pair[1]]++ outDegree[pair[0]].add(pair[1]) }
inDegree.forEachIndexed() { index, value -> if (value == 0) queue.addLast(index) }
while (queue.isNotEmpty()) { val course = queue.removeFirst() for (unlockedCourse in outDegree[course]) { prerequisiteMap[unlockedCourse].addAll(prerequisiteMap[course]) prerequisiteMap[unlockedCourse].add(course) if (--inDegree[unlockedCourse] == 0) { queue.add(unlockedCourse) } } }