[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 ...
随机推荐
- poj 3271 Lilypad Pond bfs
因为有了1的存在,使得问题变得比较难搞了,所以比较简单的做法就是把1去掉,先做一次bfs,处理出每个点能够一步到达的点(一定是1步). 然后就可以在新图上用bfs算出两个点之间的最短路,和最短路的个数 ...
- [AngularJS] ngMessageFormat
ngMessageFormat can be installed via npm using the following command: $ npm install angular-message- ...
- linux nohup命令
nohup 命令 用途:不挂断地运行命令.如果你正在执行一个job,并且你希望在退出帐户/关闭终端之后继续运行,可以使用nohup命令.nohup就是不挂起的意思( no hang up). 语法:n ...
- Windows离线安装.NET3.X
Windows离线安装.NET3.X 当我们在Windows上安装软件的时候,总是会提示需要安装.NET3.X.而大多数人们选择在线安装,这样会很慢,不少人想到了离线安装的方式.其是只要你的电脑是Wi ...
- phpmyadmin登陆提示#2002 无法登录 MySQL 服务器和设置自增
看看mysql启动没有,结果是mysql服务没有启动,找了半天,是这个原因,那就右键计算机->管理->服务->启动mysql服务 设置自增:在显示出来的一行字段定义中把浏览器的滚动条 ...
- HashTable 及应用
HashTable-散列表/哈希表,是根据关键字(key)而直接访问在内存存储位置的数据结构. 它通过一个关键值的函数将所需的数据映射到表中的位置来访问数据,这个映射函数叫做散列函数,存放记录的数组叫 ...
- php中curl、fsockopen的应用
最近要用到通过post上传文件,网上盛传的有curl的post提交和fsockopen,其中curl最简单,于是从最简单的说起. 这是简单的将一个变量post到另外一个页面 $url = ''; $d ...
- 自己动手写框架——IoC的实现
先看看 IoC百度百科 优化过程 namespace Test { class Program { static void Main(string[] args) { //场景 某公司客服要回访一些客 ...
- image控件读取数据库二进制图片
DataGridShowImage.aspx <%@ Page language="c#" debug="true" Codebehind=" ...
- python requests 基础学习
首先,Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 不友好.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来 ...