leetcode.210. Course Schedule II
2016-05-13 20:47
337 查看
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, 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.
For example:
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
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
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, 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.
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 the correct course order is
[0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
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].
class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { map<int,int> count; vector<int> res; 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); //将入度为零的点压入队列 res.push_back(i); } } 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); res.push_back(prerequisites[i].first); } } } } if(res.size()==numCourses) return res; vector<int> ans; return ans; } };
相关文章推荐
- hdu1848Fibonacci again and again
- (OK) Docker中使用固定IP——docker run -i -t --rm --net='none'
- 博客花园典型用户和场景
- C#界面闪烁问题解决方案
- 安卓摇一摇
- 使用TextView实现跑马灯的效果
- 后台开发面试题总结
- 后缀数组(SA)模版
- UVA 725 Division (暴力)
- Struts2 利用拦截器 interceptor 控制登陆和访问权限
- Struts2 利用拦截器 interceptor 控制登陆和访问权限
- 2013年第四届蓝桥杯C/C++程序设计本科B组决赛 猜灯谜(结果填空)
- java 用代码实现判断字符串的开头和结尾
- 用户场景分析--软件工程概论
- Quartus14.1中Qsys无法更新custom component的问题
- ubuntu kvm 部署安装 快照
- 基于MySQL实现按距离排序、范围查找
- Gradle中文使用文档
- XML系列:(5)XML解析-JAXP的DOM解析方式修改XML
- Qt中的MDI多对话框程序框架