-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 179.java
More file actions
43 lines (34 loc) · 1 KB
/
Day 179.java
File metadata and controls
43 lines (34 loc) · 1 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
import java.util.*;
class Solution {
public boolean canFinish(int n, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
int[] indegree = new int[n];
for (int[] p : prerequisites) {
int course = p[0];
int prereq = p[1];
graph.get(prereq).add(course);
indegree[course]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
int count = 0;
while (!queue.isEmpty()) {
int curr = queue.poll();
count++;
for (int neighbor : graph.get(curr)) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return count == n;
}
}