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, is it possible for you to finish all courses?
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 it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
基本思路:拓扑排序
课程之间有依赖。
1.找出那些前置条件已经具备的课程进行学习。
2.学完该课程后,更新依赖该门课程的其他课程。
3. 重复步骤1和2.
算法中,维持一个度数数组,或者称前置课程数组degree。表示要学习该课程时,尚需要学习的前置课程数。
如果其值为0,则该课程可以开始学习了。
class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> degree(numCourses); unordered_set<int> finished_courses; for (auto p: prerequisites) ++degree[p.first]; for (int i=0; i<numCourses; i++) { if (!degree[i]) finished_courses.insert(i); } int count = 0; while (!finished_courses.empty()) { int course = *finished_courses.begin(); finished_courses.erase(finished_courses.begin()); for (auto p: prerequisites) { if (p.second == course && !--degree[p.first]) finished_courses.insert(p.first); } ++count; } return count == numCourses; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。