class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map<Integer,List<Integer>> graph = new HashMap<>();
for(int i = 0;i < numCourses;i++){
graph.put(i,new LinkedList<>());
}
int[] indegred = new int[numCourses];
for(int[] prerequisite : prerequisites){
graph.get(prerequisite[1]).add(prerequisite[0]);
indegred[prerequisite[0]]++;
}
Queue<Integer> queue = new LinkedList<>();
for(int i = 0;i < indegred.length;i++){
if(indegred[i] == 0){
queue.offer(i);
}
}
LinkedList<Integer> list = new LinkedList<Integer>();
while(!queue.isEmpty()){
int pos = queue.poll();
list.add(pos);
for(int next : graph.get(pos)){
indegred[next]--;
if(indegred[next] == 0){
queue.offer(next);
}
}
}
return list.size() == numCourses ? list.stream().mapToInt(i -> i).toArray() : new int[0];
}
}
|