Leetcode 207 Course Schedule
来源:互联网 发布:女神很少网络 编辑:程序博客网 时间:2024/06/04 19:20
Q:
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.
Note:
- 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.
A:
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
if (numCourses == 0 || prerequisites.empty()){
return true;
}
graph = vector<vector<int> >(numCourses);
vis = vector<int>(numCourses, 0);
for (auto i : prerequisites) {
graph[i.second].push_back(i.first);
}
for (int u = 0; u < numCourses; ++u) {
if (0 == vis[u] && !dfs(u))
return false;
}
return true;
}
private:
vector<vector<int> > graph;
vector<int> vis;
bool dfs(int u) {
vis[u] = 1;
for (auto v : graph[u]) {
if (vis[v] == 1){
return false;
}
if (dfs(v) == false){
return false;
}
}
vis[u] = 2;
return true;
}
};
- 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
- HTML5中的新特性之Ajax篇
- hdu 1400 (插头)
- 手机射频架构解析
- 继承,实现,关联,聚合,组合,依赖几种关系的介绍
- CPropertySheet的基本用法
- Leetcode 207 Course Schedule
- CNTK API文档翻译(4)——MNIST数据加载
- Android——广播初介绍
- 使用Gallery和ImageSwitcher制作图片浏览器
- 服务调用框架DataStrom
- String、StringBuffer与StringBuilder之间区别
- WMS系统开发总结-自定义菜单或者显示的表格名字
- A New Start
- POJ3686_The Windy's_最小费用流::最小权匹配