Course Schedule II
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]
.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more on how a graph is represented.
Click to show more hints.
Referring to course Schedule, the point of 0 is constantly removed, which is the next elective course.
classSolution { Public: Vector<int> FindOrder (intNumcourses, vector<pair<int,int>>&Prerequisites) {Vector<int>order; Vector<int> Outd (numcourses,0); Vector<BOOL> del (numcourses,false); Unordered_map<int, vector<int> >graph; //Construct Reverse Neighborhood graph//graph is to decrease the out-degree of a set of vertices,//When a certain vertice is deleted for(inti =0; I < prerequisites.size (); i + +) {Outd[prerequisites[i].first]++; Graph[prerequisites[i].second].push_back (Prerequisites[i].first); } intCount =0; while(Count <numcourses) { inti; for(i =0; i < numcourses; i + +) { if(Outd[i] = =0&& Del[i] = =false) Break; } if(I <numcourses) {Del[i]=true;//DeleteOrder.push_back (i); for(intj =0; J < Graph[i].size (); J + +) {//decrease the degree of vertices that links to vertice_iOUTD[GRAPH[I][J]]--; } Count++; } Else {//no vertice with 0-degreevector<int>Noorder; returnNoorder; } } returnorder; }};
"Leetcode" 210. Course Schedule II