You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
889 B

2 years ago
package class33;
import java.util.ArrayList;
public class Problem_0210_CourseScheduleII {
2 years ago
public static int[] findOrder(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
2 years ago
for (int i = 0; i < numCourses; i++) {
2 years ago
graph.add(new ArrayList<>());
2 years ago
}
2 years ago
int[] indegree = new int[numCourses];
2 years ago
for (int[] arr : prerequisites) {
int to = arr[0];
int from = arr[1];
2 years ago
graph.get(from).add(to);
indegree[to]++;
2 years ago
}
2 years ago
int[] zeroQueue = new int[numCourses];
int l = 0;
int r = 0;
2 years ago
for (int i = 0; i < numCourses; i++) {
2 years ago
if (indegree[i] == 0) {
zeroQueue[r++] = i;
2 years ago
}
}
int count = 0;
2 years ago
while (l < r) {
int cur = zeroQueue[l++];
2 years ago
count++;
2 years ago
for (int next : graph.get(cur)) {
if (--indegree[next] == 0) {
zeroQueue[r++] = next;
2 years ago
}
}
}
2 years ago
return count == numCourses ? zeroQueue : new int[0];
2 years ago
}
}