modify code

master
algorithmzuo 1 year ago
parent ada737c9c0
commit 4d29825c5a

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

Loading…
Cancel
Save