Question
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.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]
. Another correct ordering is[0,2,1,3]
.
Solution
Similar with "Course Schedule", the only difference is that we need to record path.
Note: an empty array is the array with length = 0.
public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
// This problem is to print one possible topological sort result
// First, we need to construct a directed graph in the form of adjacency list
List<Integer>[] adjacencyList = new ArrayList[numCourses];
int[] result = new int[numCourses];
int[] degree = new int[numCourses];
Arrays.fill(degree, 0);
for (int j = 0; j < numCourses; j++) {
List<Integer> tmpList = new ArrayList<Integer>();
tmpList.add(j);
adjacencyList[j] = tmpList;
}
int length = prerequisites.length;
for (int j = 0; j < length; j++) {
int[] pair = prerequisites[j];
adjacencyList[pair[1]].add(pair[0]);
degree[pair[0]]++;
} // queue is to store nodes with 0 in-degree
Queue<Integer> queue = new LinkedList<Integer>();
for (int j = 0; j < numCourses; j++) {
if (degree[j] == 0)
queue.add(j);
}
if (queue.size() == 0)
return new int[0];
int i = 0; // begin bfs
while (queue.size() > 0) {
int current = queue.remove();
result[i] = current;
List<Integer> currentList = adjacencyList[current];
for (int j = 1; j < currentList.size(); j++) {
int tmp = currentList.get(j);
degree[tmp]--;
if (degree[tmp] == 0)
queue.add(tmp);
}
i++;
}
if (i < numCourses)
return new int[0];
return result;
}
}