210 Course Schedule II
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 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: 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] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .
- [x] indegree == 0 then queue.offer(i)
- [x] if (index == numCourses) return ans otherwise return new int[0], means there is circle in the prerequistes
[x] List<Integer>[] edges = new List[numCourses];
for (int i = 0; i < numCourses; i++) {
edges[i] = new ArrayList<>();
}[x] You have to initialize all the edges first, because, later in queue for loop, you have to use edges[i].size()
[x] time : O(V + E) space : O(n)
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
if (numCourses == 0) {
return new int[0];
}
if (numCourses > 0 && (prerequisites == null || prerequisites.length == 0)) {
int[] ans = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
ans[i] = i;
}
return ans;
}
int[] ans = new int[numCourses];
int index = 0;
//indegree : dependent on others
//edges: construct the graph using adjacent matrix, adjacent list
int[] indegree = new int[numCourses];
List<Integer>[] edges = new List[numCourses];
for (int i = 0; i < numCourses; i++) {
edges[i] = new ArrayList<>();
}
for (int[] pre : prerequisites) {
indegree[pre[0]]++; // indegre[1] = 1;
edges[pre[1]].add(pre[0]); // 0 -> 1
}
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i); // offer courses with no dependencies
}
}
while(!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int head = queue.poll();
ans[index++] = head;
for (int j = 0; j < edges[head].size(); j++) {
int temp = edges[head].get(j);
indegree[temp]--;
if (indegree[temp] == 0) {
queue.offer(temp);
}
}
}
}
if (index == numCourses){
return ans;
}
return new int[0];
}
}