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. Hikari java数据库连接池实战

    环境InterlliJ2016.3  MySQL5.7.12 pom依赖: <dependency> <groupId>com.zaxxer</groupId> & ...

  2. 如何使用project制定项目计划?(附详细步骤截图)

    使用project制定项目计划可以分为六个步骤,如下图(1): 图(1)-project制定项目计划步骤 下面我们就以project2010为例,按上图所示步骤对如何制定项目计划进行详细说明: 一.创 ...

  3. Go——报错总结

    前言 前端时间抽时间看完了Go基础的一些内容,后面接着学习,记录一些错误. 错误 cannot refer to unexported name fmt.println 报错信息: # basic . ...

  4. volatile 关键词

    volatile 关键字指示一个字段可以由多个同时执行的线程修改. 出于性能原因,编译器,运行时系统甚至硬件都可能重新排列对存储器位置的读取和写入. 声明了 volatile 的字段不进行这些优化.这 ...

  5. SpringBoot整合Bubbo

    一.创建springboot_dubbo_provider项目 1 创建service层接口 public interface IDoSomeService { public String sayHi ...

  6. S1_搭建分布式OpenStack集群_09 cinder 控制节点配置

    一.创建数据库创建数据库以及用户:# mysql -uroot -p12345678MariaDB [(none)]> CREATE DATABASE cinder;MariaDB [(none ...

  7. BZOJ 4103: [Thu Summer Camp 2015]异或运算 可持久化trie

    开始想了一个二分+可持久化trie验证,比正解多一个 log 仔细思考,你发现你可以直接按位枚举,然后在可持久化 trie 上二分就好了. code: #include <bits/stdc++ ...

  8. 2019.12.06 java基础代码

    操作系统中默认码表是:gbk      (一个中文字符占两个字节): utf-8(一个中文字符占三个字节): 数据库建库时的默认码表是:拉丁码表: (1)       public class 定义: ...

  9. Prisma 2 is Coming Soon

    转自:https://www.prisma.io/blog/prisma-2-is-coming-soon-mwwfhevie993 Prisma 2 will introduce many fund ...

  10. 开源项目 06 NPOI

    using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using S ...