There is a total of n courses you have to take, labeled from 0
to n - 1
.
Some courses May has 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 fini SH all courses.
There may is multiple correct orders, you just need to return one of the them. If It is impossible-to-finish all courses, return an empty array.
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So the correct course order is[0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There is a total of 4 courses to take. To take course 3 should has finished both courses 1 and 2. Both Courses 1 and 2 should is taken after you finished course 0. So one correct course order is [0,1,2,3]
. Another correct ordering is [0,2,1,3]
.
Portal: https://leetcode.com/problems/course-schedule-ii/
Public classSolution {//test case [1,0] Public int[] FindOrder (intNumcourses,int[] Prerequisites) { int[] Map =New int[numcourses]; intn =prerequisites.length; int[] res =New int[numcourses]; for(inti=0; i<n; i++) {map[prerequisites[i][1]] + +; } Queue<Integer> que =NewLinkedlist<integer>(); intindex = numCourses-1; for(inti=0; i<numcourses; i++) { if(Map[i] = = 0) {que.add (i); Res[index--] =i; } } while(!Que.isempty ()) { intK =Que.remove (); for(inti=0; i<n; i++) { intL = prerequisites[i][1]; if(k==prerequisites[i][0]) {Map[l]--; if(Map[l] = = 0) {que.add (L); Res[index--] =l; } } } } if(Index!=-1)return New int[0]; Else returnRes; }}
Leetcode-210 (Java) Course Schedule II