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) 解题思路的更多相关文章

  1. [LeetCode] Subsets I (78) & II (90) 解题思路,即全组合算法

    78. Subsets Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a ...

  2. [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 ...

  3. leetCode 90.Subsets II(子集II) 解题思路和方法

    Given a collection of integers that might contain duplicates, nums, return all possible subsets. Not ...

  4. leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法

    Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this ...

  5. 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 ...

  6. [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 ...

  7. [LeetCode] 3. Longest Substring Without Repeating Characters 解题思路

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  8. [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 ...

  9. 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 ...

随机推荐

  1. XTU1199:Number Game

    题目描写叙述 给你一个有N个数的集合S和一个数X,推断是否存在S的一个子集,子集里的数的最小公倍数正好是X. 输入 第一行是数据组数T. 接下来有多组数据,每组数据包括两行: 第一行有2个数N和X,1 ...

  2. Task的运行过程分析

    Task的运行过程分析 Task的运行通过Worker启动时生成的Executor实例进行, caseRegisteredExecutor(sparkProperties)=> logInfo( ...

  3. 一个Nodejs的简单计算測试程序

    測试目的: 1 測试二维数组的使用 2 输出函数的使用 代码: var util = require('util'); a = 3; b = 4; c = a + b; a = []; for(i = ...

  4. [转] 用source命令执行脚本和用sh执行脚本之间的区别

    from: http://blog.csdn.net/david_xtd/article/details/8012627 问题: 有很多方式可以执行脚本, 1).source test.bsh 2). ...

  5. Android 带你玩转实现游戏2048 其实2048只是个普通的控件(转)

    1.概述 博主本想踏入游戏开放行业,无奈水太深,不会游泳:于是乎,只能继续开发应用,但是原生Android也能开发游戏么,2048.像素鸟.别踩什么来着:今天给大家带来一篇2048的开发篇,别怕不分上 ...

  6. DecimalFormat用法

    DecimalFormat用法   DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字. DecimalFormat 包含一个模式 和一组符号 符号含义: ...

  7. Java基础知识强化88:BigDecimal类之BigDecimal类引入和概述 以及 BigDecimal的使用(加减乘除)

    1. BigDecimal类概述: 由于在运算的时候,float类型和double很容易丢失精度.所以为了能够精确的表达.计算浮点数,Java提供了BigDecimal. BigDecimal:不可变 ...

  8. 用户 'IIS APPPOOL\ExportExcel' 登录失败。

    解决了前两个错误,在成功打开项目后,在访问数据库又越到如下错误 “/”应用程序中的服务器错误. 用户 'IIS APPPOOL\ExportExcel' 登录失败. 说明: 执行当前 Web 请求期间 ...

  9. Xml序列化自引用/循环引用问题1

    1.定义类 public class Student { public int ID { get; set; } public string Name { get; set; } //[XmlIgno ...

  10. 【Linux】 任务调度/计划 cron

    实时查看日志: tail -f /var/log/cron 显示任务调度 bash#crontab -u username -l 编辑 bash#crontab -u username -e 内容: ...