-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCourseSchedule.java
More file actions
38 lines (34 loc) · 1.09 KB
/
CourseSchedule.java
File metadata and controls
38 lines (34 loc) · 1.09 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
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
Set<Integer>[] dependents = new Set[numCourses];
for (int i = 0; i < numCourses; ++i) {
dependents[i] = new HashSet<>();
}
for (int i = 0; i < prerequisites.length; ++i) {
int[] edge = prerequisites[i];
dependents[edge[1]].add(edge[0]);
}
int[] numOfPrere = new int[numCourses];
for (int i = 0; i < numCourses; ++i) {
for (int j: dependents[i]) {
numOfPrere[j]++;
}
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; ++i) {
if (numOfPrere[i] == 0) {
q.offer(i);
}
}
while (!q.isEmpty()) {
int course = q.poll();
for (int i: dependents[course]) {
if (--numOfPrere[i] == 0) {
q.offer(i);
}
}
--numCourses;
}
return numCourses == 0;
}
}