-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCourseSchedule.java
66 lines (58 loc) · 2.14 KB
/
CourseSchedule.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// https://leetcode.com/problems/course-schedule
// T: O(|pre-requisites| + numCourses)
// S: O(numCourses)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class CourseSchedule {
public boolean canFinish(int numCourses, int[][] prerequisites) {
final int[] inDegree = getInDegreeValues(prerequisites, numCourses);
final Queue<Integer> queue = queueWithInDegree0Vertices(inDegree);
final Map<Integer, List<Integer>> graph = getDependencyGraph(prerequisites);
while (!queue.isEmpty()) {
int vertex = queue.poll();
if (graph.containsKey(vertex)) {
for (int adjacent : graph.get(vertex)) {
inDegree[adjacent]--;
if (inDegree[adjacent] == 0) queue.add(adjacent);
}
}
}
return allAreZero(inDegree);
}
private boolean allAreZero(int[] array) {
for (int element : array) {
if (element != 0) return false;
}
return true;
}
private Queue<Integer> queueWithInDegree0Vertices(int[] inDegrees) {
final Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < inDegrees.length; i++) {
if (inDegrees[i] == 0) {
queue.add(i);
}
}
return queue;
}
private static int[] getInDegreeValues(int[][] preRequisites, int numCourses) {
int[] result = new int[numCourses];
for (int[] preRequisite: preRequisites) {
result[preRequisite[1]]++;
}
return result;
}
private static Map<Integer, List<Integer>> getDependencyGraph(int[][] prerequisites) {
final Map<Integer, List<Integer>> dependencyGraph = new HashMap<>();
for (int[] prerequisite : prerequisites) {
if (!dependencyGraph.containsKey(prerequisite[0])) {
dependencyGraph.put(prerequisite[0], new ArrayList<>());
}
dependencyGraph.get(prerequisite[0]).add(prerequisite[1]);
}
return dependencyGraph;
}
}