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 {
1 year 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++) {
1 year ago
graph.add(new ArrayList<>());
2 years ago
}
1 year ago
int[] indegree = new int[numCourses];
2 years ago
for (int[] arr : prerequisites) {
int to = arr[0];
int from = arr[1];
1 year ago
graph.get(from).add(to);
indegree[to]++;
2 years ago
}
1 year ago
int[] zeroQueue = new int[numCourses];
int l = 0;
int r = 0;
2 years ago
for (int i = 0; i < numCourses; i++) {
1 year ago
if (indegree[i] == 0) {
zeroQueue[r++] = i;
2 years ago
}
}
int count = 0;
1 year ago
while (l < r) {
int cur = zeroQueue[l++];
2 years ago
count++;
1 year ago
for (int next : graph.get(cur)) {
if (--indegree[next] == 0) {
zeroQueue[r++] = next;
2 years ago
}
}
}
1 year ago
return count == numCourses ? zeroQueue : new int[0];
2 years ago
}
}