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
Given n =2, prerequisites =[[1,0]]
Return[0,1]
Given n = 4, prerequisites =[1,0],[2,0],[3,1],[3,2]]
Return[0,1,2,3]or[0,2,1,3]
public int[] findOrder(int numCourses, int[][] prerequisites) {
//Initial the adjacency list
List<ArrayList<Integer>> adjacencyList=new ArrayList<ArrayList<Integer>>();
for(int i=0;i<numCourses;i++){
adjacencyList.add(new ArrayList<Integer>());
}
//Create the indegree array
int[] indegree=new int[numCourses];
//Fill the adjacencyList
for(int i=0;i<prerequisites.length;i++){
int a=prerequisites[i][1];
int b=prerequisites[i][0];
adjacencyList.get(a).add(b);
indegree[b]++;
}
//Initial the queue and push in=0 into queue
Queue<Integer> queue=new LinkedList<Integer>();
for(int i=0;i<numCourses;i++){
if(indegree[i]==0){
queue.offer(i);
}
}
int [] result=new int[numCourses];
//count is for identifying index of node
int index=0;
while(!queue.isEmpty()){
int current=queue.poll();
result[index]=current;
index++;
for(Integer node: adjacencyList.get(current)){
indegree[node]--;
if(indegree[node]==0){
queue.offer(node);
}
}
}
if(index==numCourses){
return result;
}
return new int[0];
}