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

g0201_0300.s0207_course_schedule.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
package g0201_0300.s0207_course_schedule

// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Depth_First_Search
// #Breadth_First_Search #Graph #Topological_Sort
// #2022_09_09_Time_416_ms_(40.10%)_Space_48.5_MB_(75.40%)

class Solution {
    fun canFinish(numCourses: Int, prerequisites: Array): Boolean {
        val adj: Array?> = arrayOfNulls>(numCourses)
        for (i in 0 until numCourses) {
            adj[i] = ArrayList()
        }
        for (pre in prerequisites) {
            adj[pre[1]]?.add(pre[0])
        }
        val colors = IntArray(numCourses)
        for (i in 0 until numCourses) {
            if (colors[i] == WHITE && !adj[i]?.isEmpty()!! && hasCycle(adj, i, colors)) {
                return false
            }
        }
        return true
    }

    private fun hasCycle(adj: Array?>, node: Int, colors: IntArray): Boolean {
        colors[node] = GRAY
        for (nei in adj[node]!!) {
            if (colors[nei] == GRAY) {
                return true
            }
            if (colors[nei] == WHITE && hasCycle(adj, nei, colors)) {
                return true
            }
        }
        colors[node] = BLACK
        return false
    }

    companion object {
        private const val WHITE = 0
        private const val GRAY = 1
        private const val BLACK = 2
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy