descrption
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:
1.The input prerequisites is a graph represented by a list of edges, not adjacency matrices.
2.You may assume that there are no duplicate edges in the input prerequisites.解题思路
这道题是前一篇文章中Course Schedule的扩展。前面那道题只是让我们去判断有向图中是否有环存在,这道题是让我们给出一个正确的拓朴顺序,那么就很好解决了。在上一道题目的代码中稍加修改就好,将找到的入度为0的node依次存入vector中,如果碰到有环的情况就将vector清空,最后将vector返回就好。代码如下
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
//记录正确的上课顺序
vector<int> order;
//记录每个节点的入度和从该节点发出的边
vector<int> indegree(numCourses, 0);
unordered_map<int, multiset<int>> hash;
for(auto val:prerequisites){
indegree[val.first]++;
hash[val.second].insert(val.first);
}
//遍历每个节点,找到入度为0的节点删除,并将指向节点的入度减1
for(int i = 0; i< numCourses; i++){
int j = 0;
for(j = 0; j < numCourses; j++){
if(indegree[j] == 0) break;
}
if(j == numCourses){
//order = null;
order.clear();
return order;
}
indegree[j] --;
//将入度为0的node压入vector
order.push_back(j);
for(auto val:hash[j]) indegree[val]--;
}
return order;
}
};