classSolution{List<Integer> res;publicint[]findOrder(int numCourses,int[][] prerequisites){ArrayList<Integer>[] prereq =newArrayList[numCourses];// Init. prereqfor(int i =0; i < numCourses;++i){
prereq[i]=newArrayList<Integer>();}// Add elements to prereqfor(int[] prerequisite : prerequisites){
prereq[prerequisite[0]].add(prerequisite[1]);}
res =newArrayList<>();HashSet<Integer> visit =newHashSet<>();HashSet<Integer> cycle =newHashSet<>();for(int i =0; i < numCourses;++i){if(dfs(i, visit, cycle, prereq)==false)returnnewint[0];}// After checking all the coursesreturn res.stream().mapToInt(i -> i).toArray();}privatebooleandfs(int course,HashSet<Integer> visit,HashSet<Integer> cycle,ArrayList<Integer>[] prereq
){// Impossible to finishif(cycle.contains(course)){returnfalse;}// No need to proceed if visited alreadyif(visit.contains(course)){returntrue;}// Add the course
cycle.add(course);// Check the pre of the coursefor(int pre : prereq[course]){// Check validityif(dfs(pre, visit, cycle, prereq)==false)returnfalse;}// After checking all pre, back to the course
cycle.remove(course);
visit.add(course);// The course is able to be taken
res.add(course);returntrue;}}