leetcode 207: Course Schedule
来源:互联网 发布:sql中in与all的区别 编辑:程序博客网 时间:2024/05/16 07:17
To solve the problem, we need to understand the problem in another way, which is whether there is a cycle in a directed graph. The algorithm we can use is Topological Sort.
First we need to set up an adjacency list to save the graph. Then use the queue and push into all vertices having 0 in-degree. While popping the vertices in the queue, reduce the in-degree of the vertices that are connected to, and push those having 0 in-degree into the queue. Finally, if all vertices have 0 in-degree, the graph does not contain a cycle.
class Solution {public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { unordered_map<int,vector<int> > pre; vector<int> in_num(numCourses,0); int n=prerequisites.size(); for(int i=0;i<n;i++) { pre[prerequisites[i].first].push_back(prerequisites[i].second); in_num[prerequisites[i].second]++; } queue<int> q; int count=0; for(int i=0;i<numCourses;i++) if(in_num[i]==0) { q.push(i); count++; } while(!q.empty()) { int curr_course=q.front(); q.pop(); for(int i=0;i<pre[curr_course].size();i++) { int temp_course=pre[curr_course][i]; in_num[temp_course]--; if(in_num[temp_course]==0) { q.push(temp_course); count++; } } } if(count!=numCourses) return false; return true; }};
0 0
- LeetCode 207 - Course Schedule
- leetcode 207: Course Schedule
- LeetCode 207-Course Schedule
- 【Leetcode】Course Schedule #207
- LeetCode 207 Course Schedule
- LeetCode(207)Course Schedule
- leetcode 207: Course Schedule
- [LeetCode 207] Course Schedule
- 【LEETCODE】207-Course Schedule
- LeetCode 207 Course Schedule
- LeetCode 207 Course Schedule
- LeetCode 207 Course Schedule
- Leetcode 207 Course Schedule
- Leetcode 207 Course Schedule
- leetcode(207). Course Schedule
- Leetcode-207: Course Schedule
- LeetCode #207 Course Schedule
- leetcode 207 Course Schedule
- UI空间大全
- 【图论】[二分图匹配] 模板
- HDU2473 - Junk-Mail Filter 利用虚拟数组实现删除并查集的节点
- 背包问题(课件内容(讲解,容易理解))
- 【图论】【A*搜索】[POJ2449]Remmarguts' Date
- leetcode 207: Course Schedule
- C/C++编程题之整数转IP地址
- 第49讲:Scala中Variance代码实战及其在Spark中的应用源码解析学习笔记
- codeforces 121C C. Lucky Permutation(数论+构造)
- 动态规划之最大子序列和
- LeetCode题解:Happy Number
- test 2.2-2
- 【图论】【二分图匹配】[HDU2819]Swap
- 搜索技巧