博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Course Schedule II 课程清单之二
阅读量:6225 次
发布时间:2019-06-21

本文共 2397 字,大约阅读时间需要 7 分钟。

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 .

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.  - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via .

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

class Solution {public:    vector
findOrder(int numCourses, vector
>& prerequisites) { vector
res; vector
> graph(numCourses, vector
(0)); vector
in(numCourses, 0); for (auto &a : prerequisites) { graph[a.second].push_back(a.first); ++in[a.first]; } queue
q; for (int i = 0; i < numCourses; ++i) { if (in[i] == 0) 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] == 0) q.push(a); } } if (res.size() != numCourses) res.clear(); return res; }};

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
查找 EXC_BAD_ACCESS 问题根源的方法
查看>>
iOS设置app应用程序文件共享
查看>>
Huawei warns against 'Berlin Wall' in digital world
查看>>
双机调试和windbg的命令
查看>>
UVA 11093 Just Finish it up 环形跑道 (贪心)
查看>>
BLOG同步测试
查看>>
编码规约
查看>>
MySQL注入时语句中的/*!0
查看>>
爬虫,基于request,bs4 的简单实例整合
查看>>
函数基础
查看>>
qdoj.xyz 6.22
查看>>
js随机背景颜色
查看>>
NTFS文件系统简介
查看>>
[IOC]Unity使用
查看>>
PUTTY的使用教程
查看>>
永远的经典-意大利波伦塔蛋糕Polenta Cake
查看>>
[转载] C#面向对象设计模式纵横谈——22 State状态模式
查看>>
HDOJ_ACM_Max Sum
查看>>
LeetCode 141, 142. Linked List Cycle I+II
查看>>
管道函数
查看>>