-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
31 lines (31 loc) · 899 Bytes
/
Solution.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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] edges = new List[numCourses];
for (int i = 0; i < numCourses; ++i) {
edges[i] = new ArrayList<>();
}
int[] indegree = new int[numCourses];
for (int[] p : prerequisites) {
int a = p[0], b = p[1];
edges[b].add(a);
++indegree[a];
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) {
q.offer(i);
}
}
int n = 0;
while (!q.isEmpty()) {
int b = q.poll();
++n;
for (int a : edges[b]) {
if (--indegree[a] == 0) {
q.offer(a);
}
}
}
return n == numCourses;
}
}