forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule II.java
41 lines (37 loc) · 1.21 KB
/
Course Schedule II.java
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
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
int[] inDegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
graph.put(i, new HashSet<Integer>());
}
for (int[] pair : prerequisites) {
graph.get(pair[1]).add(pair[0]);
inDegree[pair[0]]++;
}
// BFS - Kahn's Algorithm - Topological Sort
Queue<Integer> bfsContainer = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) {
bfsContainer.add(i);
}
}
int count = 0;
int[] ans = new int[numCourses];
while (!bfsContainer.isEmpty()) {
int curr = bfsContainer.poll();
ans[count++] = curr;
for (Integer num : graph.get(curr)) {
inDegree[num]--;
if (inDegree[num] == 0) {
bfsContainer.add(num);
}
}
}
if (count < numCourses) {
return new int[] {};
} else {
return ans;
}
}
}