Schedule II

The title

Version 1 is correct

Map<Integer, List<Integer>> edgesMap = new HashMap<>(); // Mark the state of each node: 0= unsearched, 1= searching, 2= completed int[] visited; Boolean loop = Boolean.FALSE; Int [] ans; Int index; int index; int index; int index; int index; Public int[] findOrder(int numCourses, int[][] prerequisites) {public int[] findOrder(int numCourses, int[][] prerequisites) {// Typical topology ordering problem: // For any directed edge (u, v) in graph G, u appears before V in the permutation. // The directed edge (u, v) means that node u points to node V, that is, u is a precondition of V. // If there are rings in the graph, then topological ordering cannot be solved. // The reason is that the essence of the problem is to give a list of all the courses, and then satisfy the preposition of each course X that y precedes x in the list // just as topological ordering requires directed edge nodes // So each course can be regarded as a node in a directed graph, // Start from 0 to numcourses-1 // Start from 0 to numcourses-1 // Start from 0 to numcourses-1 // For (int I = 0; i < prerequisites.length; // Order [1] indicates order[0] int [] ORDER = resident [I]; // Order [1] indicates order[0] int = resident [I]; List<Integer> temp = edgesMap.getOrDefault(order[1], new ArrayList<>()); if (! temp.contains(order[0])) { temp.add(order[0]); edgesMap.put(order[1], temp); // DFS visited = new int[numCourses]; // DFS visited = new int[numCourses]; ans = new int[numCourses]; index = numCourses - 1; for (int i = 0; i < numCourses; i ++) { if (visited[i] == 0) { dfs(i); } // If (loop) {return new int[0]; } } return ans; } public void DFS (int u) {public void DFS (int u) {public void DFS (int u) { [u] = 1; EdgesMap,get(u) may be null for (int v: Edgesmap. getOrDefault(u, new ArrayList<>())) {// If (visited[v] == 0) {DFS (v); if (loop) { return; Else if (visited[v] == 1) {loop = boolea.true; return; // Mark the node as "completed" after searching all the directed edges of a node as the starting point; // Add the node to the result ans[index] = u; index --; }Copy the code

The right reason

(1) How to convert the problem into a directed graph

(2) How to judge whether there is a ring? When is the node marked as completed and when is it added to the result array

(3) If there is a ring, truncate it and return it in time