-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
38 lines (34 loc) · 1.08 KB
/
Solution.java
File metadata and controls
38 lines (34 loc) · 1.08 KB
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
package courseSchedule;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>(numCourses);
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<Integer>());
}
int[] valencies = new int[numCourses];
for (int[] pre : prerequisites) {
graph.get(pre[0]).add(pre[1]);
valencies[pre[1]]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (valencies[i] == 0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
int currentCourse = queue.poll();
numCourses--;
for (int nextCourse : graph.get(currentCourse)) {
if (--valencies[nextCourse] == 0) {
queue.add(nextCourse);
}
}
}
return numCourses == 0;
}
}