[LeetCode] Course Schedule I (207) & II (210) 解题思路
207. Course Schedule
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.
问题:已知课程数量,以及各个课程间的依赖关系,求是否可以满足所有依赖关系把课程上完。
这是典型的拓扑排序应用场景。是否满足所有依赖关系,实际上就是求,在课程为节点、依赖关系为边的图中,是否存在环。若存在还,则不可能满足所有依赖关系把课程上完,反之,则可能。
使用DFS 方式遍历图中的节点。使用白、灰、黑三种颜色表示 DFS 在图中遍历进度。
当前节点被访问时的颜色含义:
- 白色:当前节点首次被访问。说明可以继续深度探索。
- 灰色:当前节点已在当前的 DFS 路径中。说明存在环。
- 黑色:当前节点已经从节点出发的后续路径已全部被访问。
判断1 : 一个节点以及从该节点出发的后续路径是否存在环:
- 若该节点为白色,则将颜色改为灰色,表示该节点已在搜索路径上。继续深度遍历节点的邻居节点,直达所有邻接节点已经邻居节点的后续节点都已全部被访问,将该节点改为黑色。不存在环。
- 若该节点为灰色,表示该节点以及在 DFS 搜索路径上,存在环。退出程序。
- 若该节点为黑色,表示节点已经后续路径已全部被访问,无需在探索。不存在环。
对所有节点都进行判断1 检查,即可知道图中是否存在环。
const int WHITE = ;
const int GRAY = ;
const int BLACK = ; class gnode{
public:
int val;
int col;
vector<gnode*> neighbours; gnode(int val){
this->val = val;
}
}; // 当要访问的节点颜色为灰色时,表示该节点已在搜索路径中,则形成了环。有还,无法完成。
bool canFinshNode(gnode* node){ if (node->col == WHITE) {
node->col = GRAY;
}else if(node->col == BLACK){
return true;
}else{
// be gray
return false;
} for (int i = ; i < node->neighbours.size(); i++) {
gnode* tmpn = node->neighbours[i];
bool res = canFinshNode(tmpn);
if (res == false) {
return false;
}
} node->col = BLACK; return true;
} bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { map<int, gnode*> val_node;
for (int i = ; i < numCourses; i++) {
gnode* node = new gnode(i);
node->col = WHITE;
val_node[i] = node;
} pair<int, int> pp;
for (int i = ; i < prerequisites.size(); i++) {
pp = prerequisites[i];
val_node[pp.second]->neighbours.push_back(val_node[pp.first]);
} map<int, gnode*>::iterator m_iter;
for (m_iter = val_node.begin(); m_iter != val_node.end(); m_iter++) {
if (m_iter->second->col == WHITE) { bool res = canFinshNode(m_iter->second);
if (res == false) {
return false;
}
}
} return true;
}
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.
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].
问题:和上面问题相似,不同的是需要额外求出可行的一个课程安排顺序。
典型的拓扑排序问题,而且这次需要求确切的拓扑顺序。
虽然 问题1 中的代码只回答了是否有可能存在拓扑顺序,但是,实际上在求解过程中已经将拓扑顺序求出来了。所有只需要将少量代码,将求出的顺序保存并返回即可。
当一个节点变为黑色,则表示该节点课程所依赖的后续课程都已排序,新变黑得节点就是下一个被排序的课程。
const int WHITE = ;
const int GRAY = ;
const int BLACK = ; class gnode{
public:
int val;
int col;
vector<gnode*> neighbours; gnode(int val){
this->val = val;
}
}; vector<int> resVec; /**
* To varify if the path which souce is node has a circle .
* If has a circle, return false;
* If has no circle, push node into res vector after visit the neighbours of node, and return true;
*
*/
bool visit(gnode* node){ if (node->col == WHITE) {
node->col = GRAY;
}else if (node->col == BLACK){
return true;
}else{
// be Gray, has a circle.
return false;
} for (int i = ; i < node->neighbours.size(); i++) {
gnode* tmp = node->neighbours[i];
int res = visit(tmp);
if (res == false) {
return false;
}
} node->col = BLACK; resVec.push_back(node->val); return true;
} vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> emptyV; // draw the graph representing the prerequisities relationship
map<int, gnode*> val_node;
for (int i = ; i < numCourses; i++) {
gnode* node = new gnode(i);
node->col = WHITE;
val_node[i] = node;
} for (int i = ; i < prerequisites.size(); i++) {
pair<int, int> pp = prerequisites[i];
val_node[pp.second]->neighbours.push_back(val_node[pp.first]);
} map<int, gnode*>::iterator m_iter;
for (m_iter = val_node.begin(); m_iter != val_node.end(); m_iter++) {
if (m_iter->second->col == WHITE) {
bool res = visit(m_iter->second);
if (res == false) {
return emptyV;
}
}
} // has a variable order
vector<int> resOdr(resVec.size());
for (int i = ; i < resVec.size(); i++) {
resOdr[i] = resVec[resVec.size() - i - ];
} return resOdr;
}
参考思路:
《算法导论》22.3 深度优先搜索, P349
《算法导论》22.4 拓扑排序, P355
[LeetCode] Course Schedule I (207) & II (210) 解题思路的更多相关文章
- [LeetCode] Subsets I (78) & II (90) 解题思路,即全组合算法
78. Subsets Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a ...
- [LeetCode] Search in Rotated Sorted Array I (33) && II (81) 解题思路
33. Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you be ...
- leetCode 90.Subsets II(子集II) 解题思路和方法
Given a collection of integers that might contain duplicates, nums, return all possible subsets. Not ...
- leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法
Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this ...
- leetCode 82.Remove Duplicates from Sorted List II (删除排序链表的反复II) 解题思路和方法
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...
- [LeetCode] 160. Intersection of Two Linked Lists 解题思路
Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...
- [LeetCode] 3. Longest Substring Without Repeating Characters 解题思路
Given a string, find the length of the longest substring without repeating characters. For example, ...
- [LeetCode] 129. Sum Root to Leaf Numbers 解题思路
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
Search for a Range Given a sorted array of integers, find the starting and ending position of a give ...
随机推荐
- table标签
table标签使我们最常用的的标签,在使用table标签时我们要注意一些其属性,早期我们经常使用table标签对其进行页面布局但是现在我们基本不再使用,由此可见table标签也是非常强大的一个工具. ...
- [转] When exactly does the virtual table pointer (in C++) gets set for an object?
PS: http://stackoverflow.com/questions/7934540/when-exactly-does-the-virtual-table-pointer-in-c-gets ...
- ProGuard 代码混淆
简介 Java代码是非常容易反编译的.为了很好的保护Java源代码,我们往往会对编译好的class文件进行混淆处理. ProGuard是一个混淆代码的开源项目.它的主要作用就是混淆,当然它还能对字节码 ...
- Avi视频生成缩略图时,提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”
需求:录制Avi格式视频成功后,使用DirectShow生成缩略图,由于视频录制时,宽高分辨率可调节,所以有些情况下,生成缩略图会抛出异常“尝试读取或写入受保护的内存.这通常指示其他内存已损坏”. 异 ...
- 数据库WMI 0x80041010 如何解决?
在你打开 SQL Server Configuration Manager遇到以下错误的时候,请参考下面提出的解决办法 solution: 打开cmd 命令窗口执行mofcomp.exe " ...
- Linux下快速搭建DNS服务器
一.术语解释:TTL Time To Live 缓冲保留时间ORIGIN 属于哪个域@ 代指域IN 开头需要空格SOA 一行记录类型的开始参数:forwarders {} 指向自己无法解析的域名跳转到 ...
- [转]PageRank算法
原文引自: 原文引自: http://blog.csdn.net/hguisu/article/details/7996185 感谢 1. PageRank算法概述 PageRank,即网页排名,又称 ...
- 删除所有ecshop版权和logo
前面我们已经讲过如何删除ecshop的版权,但是还有很多人不会,今天就详细的讲下如何删除所有ecshop版权和logo 前台部分: 1:去掉头部TITLE部分的ECSHOP演示站 Powered by ...
- JavaScript中的类式继承和原型式继承
最近在看<JavaScript设计模式>这本书,虽然内容比较晦涩,但是细品才发现此书内容的强大.刚看完第四章--继承,来做下笔记. 书中介绍了三种继承方式,类式继承.原型式继承和掺元类继承 ...
- phpcms v9为联动菜单字段添加验证提醒功能 解决标题不能为空
v9系统中,如果你在模型中添加了联动菜单字段就算你在字段设置中设置了最小值为1,提交内容之前你不选择联动菜单中的值,也不会出现类似类似“标题不能为空”这样的提示下面提供解决办法打开phpcms\lib ...