leetcode@ [210]Course Schedule II
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.
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]
.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
1 struct edge{ 2 int to; 3 edge(){ this->to = 0;} 4 edge(int t){ this->to = t;} 5 }; 6 class Solution { 7 public: 8 void addEdge(vector<edge> &edgelist, vector<vector<int>> &G, int from, int to){ 9 edge e = edge(to); 10 edgelist.push_back(e); 11 G[from].push_back(edgelist.size()-1); 12 } 13 /* calculate the indegree of all nodes in graph */ 14 void calInDegree(vector<int> &inDegree, vector<edge> edgelist, vector<vector<int>> G){ 15 for(int i=0;i<G.size();i++){ 16 for(int k=0;k<G[i].size();++k){ 17 edge e = edgelist[G[i][k]]; 18 ++inDegree[e.to]; 19 } 20 } 21 } 22 void topologicalSort(vector<int> &ret, vector<int> inDegree, vector<edge> edgelist, vector<vector<int>> G){ 23 stack<int> st; 24 while(!st.empty()) st.pop(); 25 for(int i=0;i<G.size();++i){ 26 if(!inDegree[i]) st.push(i); 27 } 28 while(!st.empty()){ 29 int k = st.top(); st.pop(); 30 ret.push_back(k); 31 for(int i=0;i<G[k].size();++i){ 32 edge e = edgelist[G[k][i]]; 33 --inDegree[e.to]; 34 if(!inDegree[e.to]) st.push(e.to); 35 } 36 } 37 vector<int> ans; 38 vector<int>::reverse_iterator pt=ret.rbegin(); 39 for(;pt!=ret.rend();++pt) ans.push_back(*pt); 40 ret = ans; 41 } 42 vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { 43 vector<edge> edgelist; edgelist.clear(); 44 vector<vector<int> > G(numCourses); 45 for(int i=0;i<G.size();++i) G[i].clear(); 46 vector<int> inDegree(numCourses); 47 for(int i=0;i<G.size();++i) inDegree[i]=0; 48 49 for(int i=0;i<prerequisites.size();++i){ 50 pair<int, int> pr = prerequisites[i]; 51 addEdge(edgelist, G, pr.first, pr.second); 52 } 53 54 calInDegree(inDegree, edgelist, G); 55 56 vector<int> ret; ret.clear(); 57 topologicalSort(ret,inDegree,edgelist,G); 58 59 if(ret.size() < numCourses){ret.clear(); return ret;} 60 else return ret; 61 } 62 };