This is an extension of Course Schedule. This time a valid sequence of courses is required as output.
Analysis
If we use the BFS solution of Course Schedule, a valid sequence can easily be recorded.
Java Solution
public int[] findOrder(int numCourses, int[][] prerequisites) { if(prerequisites == null){ throw new IllegalArgumentException("illegal prerequisites array"); } int len = prerequisites.length; //if there is no prerequisites, return a sequence of courses if(len == 0){ int[] res = new int[numCourses]; for(int m=0; m<numCourses; m++){ res[m]=m; } return res; } //records the number of prerequisites each course (0,...,numCourses-1) requires int[] pCounter = new int[numCourses]; for(int i=0; i<len; i++){ pCounter[prerequisites[i][0]]++; } //stores courses that have no prerequisites LinkedList<Integer> queue = new LinkedList<Integer>(); for(int i=0; i<numCourses; i++){ if(pCounter[i]==0){ queue.add(i); } } int numNoPre = queue.size(); //initialize result int[] result = new int[numCourses]; int j=0; while(!queue.isEmpty()){ int c = queue.remove(); result[j++]=c; for(int i=0; i<len; i++){ if(prerequisites[i][1]==c){ pCounter[prerequisites[i][0]]--; if(pCounter[prerequisites[i][0]]==0){ queue.add(prerequisites[i][0]); numNoPre++; } } } } //return result if(numNoPre==numCourses){ return result; }else{ return new int[0]; } } |
Use below collection :
Set[] starts = new HashSet[numCourses];
for (int i = 0; i < prerequisites.length ; i++) {
starts[prerequisites[i][1]].add(prerequisites[i][0]);
}
to replace with iterating all the prerequisites
for(int i=0; i<len; i++){
if(prerequisites[i][1]==c){
pCounter[prerequisites[i][0]]–;
if(pCounter[prerequisites[i][0]]==0){
queue.add(prerequisites[i][0]);
numNoPre++;
}
}
}
Thank you Ankit for directing to the right suggestion. I found an article topological sort DAG but the sequence always adds 0 at the end when none of my nodes are 0. They start from 1 till 12. Any idea why?
Here the link to the article I’m folllowing :
https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/
This doesn’t work. Always Returns an empty array.
again topological sort in DAG will give the correct sequence
dude, this is BFS though
this is BFS