public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
for(int i = 0; i < numCourses; i++){
adjList.add(new ArrayList<Integer>());
}
for(int i = 0; i < prerequisites.length; i++){
int start = prerequisites[i][0];
int end = prerequisites[i][1];
adjList.get(start).add(end);
}
int[] explored = new int[numCourses];
LinkedList<Integer> resTemp = new LinkedList<Integer>();
//int[] res = null;
for(int i = 0; i < numCourses; i++){
if(explored[i] == 2){
continue;
}
if(hasCycle(adjList, i, explored, resTemp)){
return new int[0];
}
}
int[] res = new int[numCourses];
for(int i = 0; i < resTemp.size(); i++){
res[i] = resTemp.get(i);
}
return res;
}
public boolean hasCycle(List<List<Integer>> adjList, int cur, int[] explored, LinkedList<Integer> res){
explored[cur] = 1;
for(int i = 0; i < adjList.get(cur).size(); i++){
int temp = adjList.get(cur).get(i);
if(explored[temp] == 1) {
return true;
} else if(explored[temp] == 0) {
if(hasCycle(adjList, temp, explored, res)){
return true;
}
}
}
explored[cur] = 2;
res.add(new Integer(cur));
return false;
}
}
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> adjList = new ArrayList<>();
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
adjList.add(new ArrayList<>());
}
for (int[] e : prerequisites) {
adjList.get(e[1]).add(e[0]);
indegree[e[0]]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
q.offer(i);
}
}
int[] res = new int[numCourses];
int k = 0;
while (!q.isEmpty()) {
int cur = q.poll();
res[k++] = cur;
for (int i : adjList.get(cur)) {
if (--indegree[i] == 0) {
q.offer(i);
}
}
}
return k == numCourses ? res : new int[0];
}
}