All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1401_1500.s1462_course_schedule_iv.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
package g1401_1500.s1462_course_schedule_iv

// #Medium #Depth_First_Search #Breadth_First_Search #Graph #Topological_Sort
// #2023_07_12_Time_512_ms_(100.00%)_Space_56.4_MB_(92.31%)

import java.util.LinkedList
import java.util.Queue

class Solution {
    fun checkIfPrerequisite(
        numCourses: Int,
        prerequisites: Array,
        queries: Array
    ): List {
        val m: MutableMap> = HashMap()
        val ind = IntArray(numCourses)
        for (p in prerequisites) {
            m.computeIfAbsent(p[1]) { _: Int? -> ArrayList() }.add(p[0])
            ind[p[0]]++
        }
        val r = Array(numCourses) { BooleanArray(numCourses) }
        val q: Queue = LinkedList()
        for (i in 0 until numCourses) {
            if (ind[i] == 0) {
                q.add(i)
            }
        }
        while (q.isNotEmpty()) {
            val j = q.poll()
            for (k in m.getOrDefault(j, ArrayList())) {
                r[k][j] = true
                for (l in r.indices) {
                    if (r[j][l]) {
                        r[k][l] = true
                    }
                }
                ind[k]--
                if (ind[k] == 0) {
                    q.offer(k)
                }
            }
        }
        val a: MutableList = ArrayList()
        for (qr in queries) {
            a.add(r[qr[0]][qr[1]])
        }
        return a
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy