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. JBoss 系列九十九:Rest WebService jBPM 6 集成演示样例

    概述 jBPM 6 提供 Rest API 供第三方应用整合使用 jBPM 6,本文演示假设通过 Rest API: 启动流程 获取流程实例信息 启动 User Task 完毕 User Task j ...

  2. angular指令浅谈

    今天在闲暇时间再次对angularjs的指令进行了初探,不探不知道一探吓一跳啊, 就一个简单的指令整整难住我了两个小时,先不说代码的逻辑是否复杂,就一些内部的一些实现让我看起来都是头疼的不行啊,不过最 ...

  3. U1总结

    import java.io.Writer; import java.util.Iterator; import javax.xml.transform.TransformerFactory; imp ...

  4. FileUpload 简单上传+小预览

    页面代码 : <form id="form1" runat="server"> <div> <asp:FileUpload ID= ...

  5. HTML中常用鼠标样式

    语法:cursor : auto | all-scroll | col-resize| crosshair | default | hand | move | help | no-drop | not ...

  6. 如何在CentOS 7上修改主机名

    如何在CentOS 7上修改主机名 在CentOS中,有三种定义的主机名:静态的(static),瞬态的(transient),和灵活的(pretty).“静态”主机名也称为内核主机名,是系统在启动时 ...

  7. php 通过ip获取地理位置

    <?php header('Content-Type:text/html;Charset=utf-8'); function GetIp(){ $realip = ''; $unknown = ...

  8. 【转】setStyleSheet用法

    [转自]http://blog.csdn.net/seanyxie/article/details/5925723 使用setStyleSheet来设置图形界面的外观: QT Style Sheets ...

  9. jS放大镜效果

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo4.aspx.cs& ...

  10. 若后台的Activity被系统回收...

    你后台的Activity被系统回收怎么办?如果后台的Activity由于某种原因被系统回收了,如何在被系统回收之前保存当前状态? 除了在栈顶的Activity,其他的Activity都有可能在内存不足 ...