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

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

Hints:
    1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
    2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
    3. Topological sort could also be done via BFS.

207. Course Schedule的拓展,解法与其类似,这里要按顺序添加要完成的课程。拓扑排序,最后加一步判断是否存在环,如果存在环则返回空集合。使用BFS和DFS均可,区别在于是按照入度还是出度来考虑。

C++:

class Solution {
public:
/**
* 完成所有的课程的顺序
* bfs拓扑排序
* @param numCourses 课程数量
* @param prerequisites 课程先序关系
* @return 能完成返回课程顺序,否则返回空
*/
vector<int> findOrder(int numCourses, vector<pair<int, int> >& prerequisites) {
vector<int> heads(numCourses, -1), degree(numCourses, 0), points, args;
pair<int, int> p;
int from, to, count = 0, len = prerequisites.size(); /* 构造有向图,邻接表 */
for (int i = 0; i < len; ++i) {
p = prerequisites[i];
from = p.second;
to = p.first;
++degree[to];
args.push_back(heads[from]);
points.push_back(to);
heads[from] = count++;
} /* bfs拓扑排序,依次移除入度为0的点 */
vector<int> ret;
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (degree[i] == 0) q.push(i);
while (!q.empty()) {
from = q.front();
ret.push_back(from); // 课程完成,添加到结果集中
q.pop();
to = heads[from];
while (to != -1) {
if(--degree[points[to]] == 0) q.push(points[to]);
to = args[to];
}
} /* 判定是否所有的点入度都为0,若是则不存在环,否则存在环 */
for (int i = 0; i < numCourses; ++i)
if (degree[i] > 0) {
ret.clear();
break;
} return ret;
}
};

C++:DFS

class Solution {
public:
/**
* 完成所有的课程的顺序
* dfs拓扑排序
* @param numCourses 课程数量
* @param prerequisites 课程先序关系
* @return 能完成返回课程顺序,否则返回空
*/
vector<int> findOrder(int numCourses, vector<pair<int, int> >& prerequisites) {
vector<int> heads(numCourses, -1), degree(numCourses, 0), points, args;
pair<int, int> p;
int from, to, count = 0, len = prerequisites.size(); /* 构造有向图,邻接表 */
for (int i = 0; i < len; ++i) {
p = prerequisites[i];
from = p.second;
to = p.first;
++degree[from];
args.push_back(heads[to]);
points.push_back(from);
heads[to] = count++;
} /* dfs拓扑排序,依次移除出度为0的点 */
vector<int> ret;
queue<int> q;
for (int i = 0; i < numCourses; ++i)
if (degree[i] == 0) q.push(i);
while (!q.empty()) {
to = q.front();
ret.push_back(to); // 课程完成添加到结果集中
q.pop();
from = heads[to];
while (from != -1) {
if(--degree[points[from]] == 0) q.push(points[from]);
from = args[from];
}
} /* 判定是否所有的点入度都为0,若是则不存在环,否则存在环 */
for (int i = 0; i < numCourses; ++i)
if (degree[i] > 0) {
ret.clear();
break;
} /* 逆序 */
reverse(ret.begin(), ret.end());
return ret;
}
};

  

  

[LeetCode] 210. Course Schedule II 课程安排II的更多相关文章

  1. Java for LeetCode 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 prer ...

  2. LeetCode 210. Course Schedule II(拓扑排序-求有向图中是否存在环)

    和LeetCode 207. Course Schedule(拓扑排序-求有向图中是否存在环)类似. 注意到.在for (auto p: prerequistites)中特判了输入中可能出现的平行边或 ...

  3. [LeetCode] 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 prereq ...

  4. Leetcode 210 Course Schedule II

    here are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prere ...

  5. [leetcode]210. Course Schedule II课程表II

    There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prereq ...

  6. (medium)LeetCode 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 prer ...

  7. 48.Course Schedule(课程安排)

    Level:   Medium 题目描述: There are a total of n courses you have to take, labeled from 0 to n-1. Some c ...

  8. [LeetCode] 207. Course Schedule 课程安排

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  9. LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++>

    LeetCode 81 Search in Rotated Sorted Array II [binary search] <c++> 给出排序好的一维有重复元素的数组,随机取一个位置断开 ...

随机推荐

  1. es题目

    1.elasticsearch了解多少,说说你们公司es的集群架构,索引数据大小,分片有多少,以及一些调优手段 .2.elasticsearch的倒排索引是什么?3.elasticsearch 索引数 ...

  2. python测试开发django-rest-framework-61.权限认证(permission)

    前言 用户登录后,才有操作当前用户的权限,不能操作其它人的用户,这就是需要用到权限认证,要不然你登录自己的用户,去操作别人用户的相关数据,就很危险了. authentication是身份认证,判断当前 ...

  3. 界面交互~Toast和模态对话框

    界面交互 名称 功能说明 wx.showToast 显示消息提示框 wx.showModal 显示模态对话框 wx.showLoading 显示 loading 提示框 wx.showActionSh ...

  4. Dict.Count

    static void Main(string[] args) { Dictionary<string, string> paraNameValueDict = new Dictionar ...

  5. Object.create 以原对象为原型创建一个新对象

    Object.create = function(o){ var Fun = function(){}; Fun.prototype = o; return new Fun(); } var peo ...

  6. tensorflow API _ 4 (Logging with tensorflow)

    TensorFlow用五个不同级别的日志信息.为了升序的严重性,他们是调试DEBUG,信息INFO,警告WARN,错误ERROR和致命FATAL的.当你配置日志记录在任何级别,TensorFlow将输 ...

  7. rust cargo 一些方便的三方cargo 子命令扩展

    内容来自cargo 的github wiki,记录下,方便使用 可选的列表 cargo-audit - Audit Cargo.lock for crates with security vulner ...

  8. pgloader 学习(五)pgloader 参考手册

    pgloader将各种来源的数据加载到PostgreSQL中.它可以转换动态读取的数据,并在加载前后提交原始SQL. 它使用COPY PostgreSQL协议将数据流式传输到服务器,并通过填充一对re ...

  9. siblings() 方法

    siblings([selected])       简介: 给定一个表示一组DOM元素的jQuery对象,该.siblings()方法允许我们在DOM树中搜索这些元素的兄弟节点,并从匹配的元素构造一 ...

  10. springboot带有进度条的上传

    一.说明 最近要做文件上传,在网上找了很久都没有一个全面的示例,特此记录下来分享给大家. 1.文件上传接口可按照springboot默认实现,也可用commons-fileupload组件,本示例使用 ...