-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207.java
More file actions
44 lines (35 loc) · 1.14 KB
/
207.java
File metadata and controls
44 lines (35 loc) · 1.14 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
39
40
41
42
43
44
//done for acc2 cat2
import java.util.*;
class Solution {
public boolean canFinish(int totalCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int index = 0; index < totalCourses; index++) {
graph.add(new ArrayList<>());
}
int[] indegree = new int[totalCourses];
for (int[] pair : prerequisites) {
int course = pair[0];
int prereq = pair[1];
graph.get(prereq).add(course);
indegree[course]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int index = 0; index < totalCourses; index++) {
if (indegree[index] == 0) {
queue.offer(index);
}
}
int completed = 0;
while (!queue.isEmpty()) {
int current = queue.poll();
completed++;
for (int neighbor : graph.get(current)) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return completed == totalCourses;
}
}