-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
41 lines (32 loc) · 979 Bytes
/
Copy pathsolution.java
File metadata and controls
41 lines (32 loc) · 979 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
41
import java.util.*;
class Solution {
public boolean canFinish(int n, int[][] prerequisites) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++)
adj.add(new ArrayList<>());
int[] indegree = new int[n];
// Build graph
for (int[] p : prerequisites) {
adj.get(p[1]).add(p[0]);
indegree[p[0]]++;
}
Queue<Integer> q = new LinkedList<>();
// Add nodes with 0 indegree
for (int i = 0; i < n; i++) {
if (indegree[i] == 0)
q.offer(i);
}
int count = 0;
// BFS
while (!q.isEmpty()) {
int node = q.poll();
count++;
for (int nei : adj.get(node)) {
indegree[nei]--;
if (indegree[nei] == 0)
q.offer(nei);
}
}
return count == n;
}
}