Now you have a total of N courses to choose, which are 0 to n-1.
Some prerequisite courses are required before taking some courses. For example, to learn lesson 0, you need to complete lesson 1 first. We use a match to represent them: [0,1]
Given the total number of courses and their prerequisites, return to the order in which you have arranged to complete all courses.
There may be multiple correct orders, you just need to return one. If it is not possible to complete all courses, an empty array is returned.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: there are 2 courses in total. To learn Lesson 1, you need to complete lesson 0 first. Therefore, 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 4 courses in total. To learn Lesson 3, you should first complete lesson 1 and lesson 2. And course 1 and course 2 should be placed after course 0.
Therefore, a correct course sequence is [0,1,2,3]. Another correct sort is [0,2,1,3].
This problem is almost the same as before, but we need to make sure that the course is completed first, in fact, the point with the entry of 0 is traversed from front to back In order, the more you traverse first, the less courses you need to complete before, and you need to confirm whether they will form a loop.
Hee hee, I have to be OK.
class Edge{
int next;
int to;
}
private int cnt;
private Edge[] g;
private int[] head;
private int[] deg;
private int[] ans;
public void add(int u,int v){
g[cnt]=new Edge();
g[cnt].to=v;
g[cnt].next=head[u];
head[u]=cnt++;
}
public int[] findOrder(int numCourses, int[][] prerequisites) {
int n=prerequisites.length;
int l=Math.max(numCourses,n);
cnt=0;
g=new Edge[l];
head=new int[l];
deg=new int[numCourses];
Arrays.fill(head,-1);
ans=new int[numCourses];
for(int i=0;i<n;++i){
add(prerequisites[i][1],prerequisites[i][0]);
++deg[prerequisites[i][0]];
}
if(!solve(numCourses)){
return new int[0];
}
return ans;
}
public boolean solve(int l){
Queue<Integer> queue=new LinkedList<Integer>();
for(int i=0;i<l;++i){
if(deg[i]==0){
queue.offer(i);
}
}
int k=0;
while (!queue.isEmpty()){
int u=queue.poll();
ans[k++]=u;
for(int i=head[u];i!=-1;i=g[i].next){
int v=g[i].to;
if(--deg[v]==0){
queue.offer(v);
}
}
}
return k==l;
}