leetcode.207. Course Schedule
2016-05-13 20:22
435 查看
There are a total of n courses you have to take, labeled from
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
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.
0to
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.
class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { map<int,int> count; for(int i=0;i<numCourses;i++){ count[i]=0; } for(int i=0;i<prerequisites.size();i++){ count[prerequisites[i].first]++; //计算入度 } queue<int> que; for(int i=0;i<count.size();i++){ if(count[i]==0){ que.push(i); //将入度为零的点压入队列 } } int total=que.size(); while(!que.empty()){ int cur=que.front(); que.pop(); for(int i=0;i<prerequisites.size();i++){ if(prerequisites[i].second==cur){ count[prerequisites[i].first]--; if(count[prerequisites[i].first]==0){ que.push(prerequisites[i].first); total++; } } } } return total==numCourses; } };
相关文章推荐
- 蓝桥杯 兰顿蚂蚁
- POJ 1442 Black Box(treap树)
- 数据库连接池的几种配置方法
- word2016怎么从第三页开始设置页码
- 团队冲刺第七天
- 分别使用委托、接口、匿名方法、泛型委托实现加减乘除运算
- 学习Android studio 个人总结小经验
- 共享库的概念
- 欢迎使用CSDN-markdown编辑器
- 皇宫看守 树形DP
- Java设计模式
- PAT乙级—1027. 打印沙漏(20)-native
- ural 1039 没有上司的晚会 树形dp
- 团队冲刺第六天
- 探索推荐引擎内部的秘密,第 1 部分: 推荐引擎初探
- startActivityForResult的resultCode总是为0的问题
- 顺序栈(Sequential Stack)
- 小白排序之选择排序
- HTML5培训第13节课堂笔记(mui绑定事件、预加载页面传值、懒加载、tabbar的切换)
- 通知的简单运用