-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseSchedule.java
More file actions
40 lines (32 loc) · 972 Bytes
/
courseSchedule.java
File metadata and controls
40 lines (32 loc) · 972 Bytes
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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
for (int[] p : prerequisites) {
int a = p[0], b = p[1];
graph.get(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 count = 0;
while (!q.isEmpty()) {
int curr = q.poll();
count++;
for (int nei : graph.get(curr)) {
indegree[nei]--;
if (indegree[nei] == 0) {
q.offer(nei);
}
}
}
return count == numCourses;
}
}