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. Collection子接口(List/Set/Queue/SortedSet)

    Collection基本的子接口: List:能够存放反复内容 Set:不能存放反复内容,全部反复的内容靠hashCode()和equals()两个方法区分 Queue:队列接口 SortedSet: ...

  2. Java 异常处理的误区和经验总结--转载

    本文着重介绍了 Java 异常选择和使用中的一些误区,希望各位读者能够熟练掌握异常处理的一些注意点和原则,注意总结和归纳.只有处理好了异常,才能提升开发人员的基本素养,提高系统的健壮性,提升用户体验, ...

  3. Difference between Tomcat's extraResourcePaths and aliases to access an external directory--转

    Question: Simple question: In Tomcat7, what's the difference between using extraResourcePaths and al ...

  4. 线段树---HDU1754 I hate it

    这个题也是线段树的基础题,有了上一个题的基础,在做这个题就显得比较轻松了,大体都是一样的,那个是求和,这个改成求最大值,基本上思路差不多,下面是代码的实现 #include <cstdio> ...

  5. centos6 安装vsftpd

    centos6 安装vsftpd vsftpd一般选择yum安装,以下是安装和配置过程 如果是centos6想要安装的话一般是编译安装 1.安装 yum安装 yum install vsftpd 编译 ...

  6. Java sql helper[转]

    原文:http://www.cnblogs.com/beijiguangyong/archive/2011/12/10/2302737.html package sql; import java.sq ...

  7. iOS实现OAuth2.0中刷新access token并重新请求数据操作

    一.简要概述 OAuth2.0是OAuth协议的下一版本,时常用于移动客户端的开发,是一种比较安全的机制.在OAuth 2.0中,server将发行一个短有效期的access token和长生命期的r ...

  8. String 类 Copy-On-Write 技术以及使用时存在的风险

    先来看一下string 面试时的简易写法(使用的是深拷贝): class String { String() :str(]) { str[] = '\0'; } String(char* p, siz ...

  9. 关于webApi302跳转的问题

    之前会出现"服务器无法在已发送 HTTP 标头之后设置状态"的问题,本地调试不报错,但是上产线就会报错 解决的思路是: var response = Request.CreateR ...

  10. PHP微信红包的算法实现探讨

    header("Content-Type: text/html;charset=utf-8");//输出不乱码,你懂的 $total=10;//红包总额 $num=8;// 分成8 ...