There are a total of _n _courses you have to take, labeled from0ton-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:[0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input:
2, [[1,0]]
Output:
[0,1]
Explanation:
There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is
[0,1] .
Example 2:
Input:
4, [[1,0],[2,0],[3,1],[3,2]]
Output:
[0,1,2,3] or [0,2,1,3]
Explanation:
There are a total of 4 courses to take. To take course 3 you should have finished both
courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is
[0,1,2,3]
. Another correct ordering is
[0,2,1,3] .
Note:
The input prerequisites is a graph represented by a list of edges , not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
Analysis
Similar to Course Schedule, this problem just needs to return the topologically sorted results.
Hints:
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
publicint[] findOrder(int numCourses,int[][] prerequisites) {// Write your code hereList[] edges =newArrayList[numCourses];int[] degree =newint[numCourses];for (int i =0;i < numCourses; i++) edges[i] =newArrayList<Integer>();for (int i =0; i <prerequisites.length; i++) { degree[prerequisites[i][0]] ++ ; edges[prerequisites[i][1]].add(prerequisites[i][0]); }Queue queue =newLinkedList();for(int i =0; i <degree.length; i++){if (degree[i] ==0) {queue.add(i); } }int count =0;int[] order =newint[numCourses];while(!queue.isEmpty()){int course = (int)queue.poll(); order[count] = course; count ++;int n = edges[course].size();for(int i = n -1; i >=0 ; i--){int pointer = (int)edges[course].get(i); degree[pointer]--;if (degree[pointer] ==0) {queue.add(pointer); } } }if (count == numCourses)return order;returnnewint[0]; }
BFS - LeetCode Official - Using In-degree
classSolution {publicint[] findOrder(int numCourses,int[][] prerequisites) {boolean isPossible =true;Map<Integer,List<Integer>> adjList =newHashMap<Integer,List<Integer>>();int[] indegree =newint[numCourses];int[] topologicalOrder =newint[numCourses];// Create the adjacency list representation of the graphfor (int i =0; i <prerequisites.length; i++) {int dest = prerequisites[i][0];int src = prerequisites[i][1];List<Integer> lst =adjList.getOrDefault(src,newArrayList<Integer>());lst.add(dest);adjList.put(src, lst);// Record in-degree of each vertex indegree[dest] +=1; }// Add all vertices with 0 in-degree to the queueQueue<Integer> q =newLinkedList<Integer>();for (int i =0; i < numCourses; i++) {if (indegree[i] ==0) {q.add(i); } }int i =0;// Process until the Q becomes emptywhile (!q.isEmpty()) {int node =q.remove(); topologicalOrder[i++] = node;// Reduce the in-degree of each neighbor by 1if (adjList.containsKey(node)) {for (Integer neighbor :adjList.get(node)) { indegree[neighbor]--;// If in-degree of a neighbor becomes 0, add it to the Qif (indegree[neighbor] ==0) {q.add(neighbor); } } } }// Check to see if topological sort is possible or not.if (i == numCourses) {return topologicalOrder; }returnnewint[0]; }}
DFS - LeetCode Official
classSolution {staticint WHITE =1;staticint GRAY =2;staticint BLACK =3;boolean isPossible;Map<Integer,Integer> color;Map<Integer,List<Integer>> adjList;List<Integer> topologicalOrder;privatevoidinit(int numCourses) {this.isPossible=true;this.color=newHashMap<Integer,Integer>();this.adjList=newHashMap<Integer,List<Integer>>();this.topologicalOrder=newArrayList<Integer>();// By default all vertces are WHITEfor (int i =0; i < numCourses; i++) {this.color.put(i, WHITE); } }privatevoiddfs(int node) {// Don't recurse further if we found a cycle alreadyif (!this.isPossible) {return; }// Start the recursionthis.color.put(node, GRAY);// Traverse on neighboring verticesfor (Integer neighbor :this.adjList.getOrDefault(node,newArrayList<Integer>())) {if (this.color.get(neighbor) == WHITE) {this.dfs(neighbor); } elseif (this.color.get(neighbor) == GRAY) {// An edge to a GRAY vertex represents a cyclethis.isPossible=false; } }// Recursion ends. We mark it as blackthis.color.put(node, BLACK);this.topologicalOrder.add(node); }publicint[] findOrder(int numCourses,int[][] prerequisites) {this.init(numCourses);// Create the adjacency list representation of the graphfor (int i =0; i <prerequisites.length; i++) {int dest = prerequisites[i][0];int src = prerequisites[i][1];List<Integer> lst =adjList.getOrDefault(src,newArrayList<Integer>());lst.add(dest);adjList.put(src, lst); }// If the node is unprocessed, then call dfs on it.for (int i =0; i < numCourses; i++) {if (this.color.get(i) == WHITE) {this.dfs(i); } }int[] order;if (this.isPossible) { order =newint[numCourses];for (int i =0; i < numCourses; i++) { order[i] =this.topologicalOrder.get(numCourses - i -1); } } else { order =newint[0]; }return order; }}