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. 找出那些没有前置条件的课程,放入一个集合中finished。
2. 从集合中取出一个课程进行学习。并修改那些依赖本课程的课程。如果这些课程中,前置条件已经全部齐备,则放入集合finished.
3. 重复步骤1和2,直到集合finished为空。
如果此时,还有课程未被学习。则剩余课程存在循环依赖。
需要建立一个节点度数degree,以表示本课程所依赖的课程数。当该值为0时,说明前置课程已经学完,可以进行该课程学习。
同时需要一个映射graphic,确定本课程被哪些课程所依赖。 以便于学完本课程后,去更新那些课程的前置条件课程数degree。
class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> ans; vector<int> degree(numCourses); vector<vector<int> > graphic(numCourses); unordered_set<int> finished; for (auto p: prerequisites) { degree[p.first]++; graphic[p.second].push_back(p.first); } for (int i=0; i<numCourses; i++) if (!degree[i]) finished.insert(i); int count = 0; while (!finished.empty()) { auto course = *finished.begin(); finished.erase(finished.begin()); for (auto c: graphic[course]) { if (!--degree[c]) finished.insert(c); } ans.push_back(course); ++count; } if (count != numCourses) ans.clear(); return ans; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。