-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreRequisiteTasks.java
More file actions
45 lines (36 loc) · 1.06 KB
/
PreRequisiteTasks.java
File metadata and controls
45 lines (36 loc) · 1.06 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
45
package graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* Implementation of Kahn's Algorithm.
* */
public class PreRequisiteTasks {
public static boolean isPossible(int N, int P, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
int[] indegree = new int[N];
for (int i = 0; i < N; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < P; i++) {
int dest = prerequisites[i][0];
int src = prerequisites[i][1];
adj.get(src).add(dest);
indegree[dest]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < N; i++) {
if (indegree[i] == 0) q.add(i);
}
int size = 0;
while (!q.isEmpty()) {
int curr = q.poll();
size++;
for (int num : adj.get(curr)) {
indegree[num]--;
if (indegree[num] == 0) q.add(num);
}
}
return size == N;
}
}