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.

Example 1:

Input: 2, [[1,0]]
Output: [0,1]
Explanation: 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] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.
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.

这题是之前那道 Course Schedule 的扩展,那道题只让我们判断是否能完成所有课程,即检测有向图中是否有环,而这道题我们得找出要上的课程的顺序,即有向图的拓扑排序 Topological Sort,这样一来,难度就增加了,但是由于我们有之前那道的基础,而此题正是基于之前解法的基础上稍加修改,我们从 queue 中每取出一个数组就将其存在结果中,最终若有向图中有环,则结果中元素的个数不等于总课程数,那我们将结果清空即可。代码如下:

class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> res;
vector<vector<int> > graph(numCourses, vector<int>());
vector<int> in(numCourses, );
for (auto &a : prerequisites) {
graph[a.second].push_back(a.first);
++in[a.first];
}
queue<int> q;
for (int i = ; i < numCourses; ++i) {
if (in[i] == ) q.push(i);
}
while (!q.empty()) {
int t = q.front();
res.push_back(t);
q.pop();
for (auto &a : graph[t]) {
--in[a];
if (in[a] == ) q.push(a);
}
}
if (res.size() != numCourses) res.clear();
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/210

类似题目:

Minimum Height Trees

Course Schedule

Course Schedule III

Alien Dictionary

Sequence Reconstruction

参考资料:

https://leetcode.com/problems/course-schedule-ii/

https://leetcode.com/problems/course-schedule-ii/discuss/59330/Concise-JAVA-solution-based-on-BFS-with-comments

https://leetcode.com/problems/course-schedule-ii/discuss/59342/Java-DFS-double-cache-visiting-each-vertex-once-433ms

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Course Schedule II 课程清单之二的更多相关文章

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

  2. [LeetCode] Course Schedule III 课程清单之三

    There are n different online courses numbered from 1 to n. Each course has some duration(course leng ...

  3. [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 prer ...

  4. [LeetCode] Flip Game II 翻转游戏之二

    You are playing the following Flip Game with your friend: Given a string that contains only these tw ...

  5. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  6. [LeetCode] Paint House II 粉刷房子之二

    There are a row of n houses, each house can be painted with one of the k colors. The cost of paintin ...

  7. [LeetCode] Ugly Number II 丑陋数之二

    Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors ...

  8. [LeetCode] Strobogrammatic Number II 对称数之二

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...

  9. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

随机推荐

  1. ASP.NET Core 中文文档 第四章 MVC(3.6.1 )Tag Helpers 介绍

    原文:Introduction to Tag Helpers 作者:Rick Anderson 翻译:刘浩杨 校对:高嵩(Jack) 什么是 Tag Helpers? Tag Helpers 提供了什 ...

  2. Windows环境下vscode-go安装笔记

    一.介绍 对于Visual Studio Code开发工具,有一款优秀的GoLang插件,它的主页为:https://github.com/microsoft/vscode-go 这款插件的特性包括: ...

  3. 移动WEB开发之viewport

    问题: 在codepen上写了一个响应式页面,调试的时候没有问题.结果放到网站上,在手机上打开之后竟然和在电脑中的布局是一样的.         查阅资料之后知道响应式布局应该有这样一句话:<m ...

  4. 让BASH,VIM美美的Powerline

    前言  鉴于BASH及其周边强大的工具以及VIM高效快捷,加上现在我工作重心转移到前端开发上,因此我华丽地转向Linux阵营(当然从最傻瓜式的Ubuntu开始啦!).但BASH和VIM默认样式确实颜值 ...

  5. MyCat源码分析系列之——配置信息和启动流程

    更多MyCat源码分析,请戳MyCat源码分析系列 MyCat配置信息 除了一些默认的配置参数,大多数的MyCat配置信息是通过读取若干.xml/.properties文件获取的,主要包括: 1)se ...

  6. OS存储管理——FIFO,LRU,OPT命中率

    课程设计课题 存储管理程序设计 摘 要 虚拟存储器作为现代操作系统中存储管理的一项重要技术,实现了内存扩充功能.而分页请求分页系统正好可以完美的支持虚拟存储器功能,它具有请求调页功能和页面置换功能.在 ...

  7. CentOS 防火墙开放特定端口

    iptables是linux下的防火墙,同时也是服务名称.   service  iptables  status        查看防火墙状态 service  iptables  start   ...

  8. linux使用wkhtmltopdf报错error while loading shared libraries:

    官网提示 linux需要这些动态库.depends on: zlib, fontconfig, freetype, X11 libs (libX11, libXext, libXrender) 在li ...

  9. Mac下查看端口占用

    netstat命令 netstat -an | grep 端口号 lsof命令 lsof -i:端口号

  10. Android Studio多渠道打包

    本文所讲述的多渠道打包是基于友盟统计实施的. 多渠道打包的步骤: 1.在AndroidManifest.xml里设置动态渠道变量 <meta-data android:name="UM ...