[LeetCode/LintCode] Course Schedule II

NO IMAGE

Problem

There are a total of n courses you have to take, labeled from 0 to n – 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]

Solution

public class Solution {
/*
* @param n: a total of n courses
* @param pre: a list of prerequisite pairs
* @return: the course order
*/
public int[] findOrder(int n, int[][] pre) {
// write your code here
ArrayList[] graph = new ArrayList[n];
for (int i = 0; i < n; i  ) {
graph[i] = new ArrayList<Integer>();
}
int[] indegree = new int[n];
for (int i = 0; i < pre.length; i  ) {
graph[pre[i][1]].add(pre[i][0]);
indegree[pre[i][0]]  ;
}
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < n; i  ) {
if (indegree[i] == 0) queue.add(i);
}
int[] result = new int[n];
int index = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
result[index  ] = node;
ArrayList<Integer> list = graph[node];
for (int i = 0; i < list.size(); i  ) {
int cur = list.get(i);
indegree[cur]--;
if (indegree[cur] == 0) queue.add(cur);
}
}
return index == n ? result : new int[0];
}
}