Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

add kotlin solution for 207 Course-Schedule.kt #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions 73 May-LeetCoding-Challenge/29-Course-Schedule/Course-Schedule.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
class CourseScheduleKotlin207 {
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
// 1 true, -1 false, 0 not judge
val coursesArray = IntArray(numCourses)
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (pre in prerequisites) {
graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0])
}
for (index in coursesArray.indices) {
if (!dfs(index, coursesArray, graph)) {
return false
}
}
return true
}

// true -> can finish
private fun dfs(
current: Int,
coursesArray: IntArray,
graph: Map<Int, List<Int>>
): Boolean {
return when {
coursesArray[current] == -1 -> false
coursesArray[current] == 1 -> true
else -> {
coursesArray[current] = -1
graph[current]?.forEach {
if (!dfs(it, coursesArray, graph)) {
return false
}
}
coursesArray[current] = 1
true
}
}
}
/*
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
val coursesArray = IntArray(numCourses)
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (pre in prerequisites) {
graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0])
++coursesArray[pre[0]]
}
val queue: Queue<Int> = LinkedList()
coursesArray.forEachIndexed { index, i ->
if (i == 0) {
queue.offer(index)
}
}
while (queue.isNotEmpty()) {
val current = queue.poll()
graph[current]?.forEach {
if (--coursesArray[it] == 0) {
queue.offer(it)
}
}
}
return coursesArray.count { it == 0 } == numCourses
}
*/
}

fun main() {
val solution = CourseScheduleKotlin207()
// true
println(solution.canFinish(2, arrayOf(intArrayOf(0, 1))))
// false
println(solution.canFinish(2, arrayOf(intArrayOf(0, 1), intArrayOf(1, 0))))
// true
println(solution.canFinish(3, arrayOf(intArrayOf(2, 1), intArrayOf(1, 0))))
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.