C++实现LeetCode(210.课程清单之二)
[LeetCode] 210. 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.
Example 1:
Input: 2, [[1,0]]Example 2:
Output: [0,1]
Explanation: 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] .
Input: 4, [[1,0],[2,0],[3,1],[3,2]]Note:
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
- This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
class Solution {public:vectorfindOrder(int numCourses, vector>& prerequisites) {vector res; vector > graph(numCourses, vector (0)); vector in(numCourses, 0); for (auto &a : prerequisites) {graph[a.second].push_back(a.first); ++in[a.first]; }queue q; for (int i = 0; i < numCourses; ++i) {if (in[i] == 0) q.push(i); }while (!q.empty()) {int t = q.front(); res.push_back(t); q.pop(); for (auto &a : graph[t]) {--in[a]; if (in[a] == 0) q.push(a); }}if (res.size() != numCourses) res.clear(); return res; }};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/210
类似题目:
Course Schedule
参考资料:
https://leetcode.com/problems/course-schedule-ii/
https://leetcode.com/problems/course-schedule-ii/discuss/59330/Concise-JAVA-solution-based-on-BFS-with-comments
https://leetcode.com/problems/course-schedule-ii/discuss/59342/Java-DFS-double-cache-visiting-each-vertex-once-433ms
【C++实现LeetCode(210.课程清单之二)】到此这篇关于C++实现LeetCode(269.另类字典)的文章就介绍到这了,更多相关C++实现另类字典内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- java中如何实现重建二叉树
- leetcode|leetcode 92. 反转链表 II
- 人脸识别|【人脸识别系列】| 实现自动化妆