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. 从273二手车的M站点初探js模块化编程

    前言 这几天在看273M站点时被他们的页面交互方式所吸引,他们的首页是采用三次加载+分页的方式.也就说分为大分页和小分页两种交互.大分页就是通过分页按钮来操作,小分页是通过下拉(向下滑动)时异步加载数 ...

  2. jQuery-1.9.1源码分析系列(三) Sizzle选择器引擎——编译原理

    这一节要分析的东东比较复杂,篇幅会比较大,也不知道我描述后能不能让人看明白.这部分的源码我第一次看的时候也比较吃力,现在重头看一遍,再分析一遍,看能否查缺补漏. 看这一部分的源码需要有一个完整的概念后 ...

  3. react-native ListView使用详解

    刚好今天七夕,呆萌的程序猿没有妹纸,刚好发小明天结婚,我还在异地,晚上还要苦逼的赶火车.趁着下午比较闲,更新一下Blog,也算是在百无聊赖之时给众多单身程序猿们的小福利吧,虽然已经好久没更了...囧 ...

  4. MFC AfxMessageBox默认标题修改

    在工程的资源String Table里面添加AFX_IDS_APP_TITLE,然后设置其值即可,AFX_IDS_APP_TITLE的值就是AfxMessageBox的标题

  5. afxcomctl32.h与afxcomctl32.inl报错

    afxcomctl32.h与afxcomctl32.inl报错 编译公司一个几年前的老项目,是从VC6.0升级到VS2005的. 1.编译时报缺少头文件,于是附件包含目录,于是出现了以下报错: 1&g ...

  6. [C1] 实现 C1FlexGrid 撤销还原功能

    采用设计模式中的"命令模式"实现 C1FlexGrid 的撤销还原功能,那就先从命令模式简单介绍开始吧. 一  命令模式 命令模式属于对象的行为型模式,将一个请求封装为一个对象,从 ...

  7. C语言计算2个数的最小公倍数

    #include<stdio.h>int main(){   int a,b,i=1,temp,lcm;   scanf("%d %d",&a,&b); ...

  8. 数据结构:基于list实现二元表达式(python版)

    #!/usr/bin/env python # -*- coding:utf-8 -*- def make_sum(a, b): return ['+', a, b] def make_prod(a, ...

  9. IE 浏览器各个版本 JavaScript 支持情况一览表

    语言元素 语言元素 突发.IE6 标准.IE7 标准 IE8 标准 IE 9 标准 IE 10 标准 边缘 Windows 应用商店应用程序 __proto__ 属性 (Object) (JavaSc ...

  10. [转载]C#深入分析委托与事件

    原文出处: 作者:风尘浪子 原文链接:http://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html 同类链接:http://www.c ...