성능 : Time: 194 ms (74.76%), Space: 42.4 MB (38.35%)
Kotlin 풀이
```kt
class Solution {
val edges: Array> = Array(2000) { arrayListOf() }
val inDegrees: IntArray = IntArray(2000)
var n: Int = 0
fun canFinish(numCourses: Int, prerequisites: Array): Boolean {
n = numCourses
for ((u, v) in prerequisites) {
edges[u] += v
inDegrees[v]++
}
return isCompletableCourses()
}
fun isCompletableCourses(): Boolean {
val deque: ArrayDeque = ArrayDeque(n)
var completableCourse: Int = 0
for (u in 0 until n) {
if (inDegrees[u] == 0) {
deque += u
}
}
while (deque.isNotEmpty()) {
val u = deque.removeFirst()
for (v in edges[u]) {
if (--inDegrees[v] == 0) {
deque += v
}
}
completableCourse++
}
return completableCourse == n
}
}
```
코멘트
처음 접했을 때 풀기 힘든 알고리즘인 Topological Sort (위상 정렬) 문제네요
```java
class Solution {
public boolean dfs(Map> finishToTakeMap, Integer finish, List takes, List taken) {
if (takes.contains(finish))
return false;
if (taken.contains(finish))
return true;
if (finishToTakeMap.containsKey(finish)) {
takes.add(finish);
for (Integer take : finishToTakeMap.get(finish)) {
if (!dfs(finishToTakeMap, take, takes, taken))
return false;
}
takes.remove(finish);
taken.add(finish);
}
return true;
}
public boolean canFinish(int numCourses, int[][] prerequisites) {
Map> finishToTakeMap = new HashMap<>();
for (int[] pre : prerequisites) {
finishToTakeMap.putIfAbsent(pre[0], new ArrayList<>());
finishToTakeMap.get(pre[0]).add(pre[1]);
}
List takes = new ArrayList<>();
List taken = new ArrayList<>();
for (Integer finish : finishToTakeMap.keySet()) {
if (!dfs(finishToTakeMap, finish, takes, taken))
return false;
}
return true;
}
}
```
문제 링크