parent
ada737c9c0
commit
4d29825c5a
@ -1,71 +1,40 @@
|
||||
package class33;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
public class Problem_0210_CourseScheduleII {
|
||||
|
||||
public static class Node {
|
||||
public int name;
|
||||
public int in;
|
||||
public ArrayList<Node> nexts;
|
||||
|
||||
public Node(int n) {
|
||||
name = n;
|
||||
in = 0;
|
||||
nexts = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
public int[] findOrder(int numCourses, int[][] prerequisites) {
|
||||
int[] ans = new int[numCourses];
|
||||
public static int[] findOrder(int numCourses, int[][] prerequisites) {
|
||||
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
|
||||
for (int i = 0; i < numCourses; i++) {
|
||||
ans[i] = i;
|
||||
graph.add(new ArrayList<>());
|
||||
}
|
||||
if (prerequisites == null || prerequisites.length == 0) {
|
||||
return ans;
|
||||
}
|
||||
HashMap<Integer, Node> nodes = new HashMap<>();
|
||||
int[] indegree = new int[numCourses];
|
||||
for (int[] arr : prerequisites) {
|
||||
int to = arr[0];
|
||||
int from = arr[1];
|
||||
if (!nodes.containsKey(to)) {
|
||||
nodes.put(to, new Node(to));
|
||||
}
|
||||
if (!nodes.containsKey(from)) {
|
||||
nodes.put(from, new Node(from));
|
||||
graph.get(from).add(to);
|
||||
indegree[to]++;
|
||||
}
|
||||
Node t = nodes.get(to);
|
||||
Node f = nodes.get(from);
|
||||
f.nexts.add(t);
|
||||
t.in++;
|
||||
}
|
||||
int index = 0;
|
||||
Queue<Node> zeroInQueue = new LinkedList<>();
|
||||
int[] zeroQueue = new int[numCourses];
|
||||
int l = 0;
|
||||
int r = 0;
|
||||
for (int i = 0; i < numCourses; i++) {
|
||||
if (!nodes.containsKey(i)) {
|
||||
ans[index++] = i;
|
||||
} else {
|
||||
if (nodes.get(i).in == 0) {
|
||||
zeroInQueue.add(nodes.get(i));
|
||||
}
|
||||
if (indegree[i] == 0) {
|
||||
zeroQueue[r++] = i;
|
||||
}
|
||||
}
|
||||
int needPrerequisiteNums = nodes.size();
|
||||
int count = 0;
|
||||
while (!zeroInQueue.isEmpty()) {
|
||||
Node cur = zeroInQueue.poll();
|
||||
ans[index++] = cur.name;
|
||||
while (l < r) {
|
||||
int cur = zeroQueue[l++];
|
||||
count++;
|
||||
for (Node next : cur.nexts) {
|
||||
if (--next.in == 0) {
|
||||
zeroInQueue.add(next);
|
||||
for (int next : graph.get(cur)) {
|
||||
if (--indegree[next] == 0) {
|
||||
zeroQueue[r++] = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count == needPrerequisiteNums ? ans : new int[0];
|
||||
return count == numCourses ? zeroQueue : new int[0];
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
Reference in new issue