[LeetCode] Course Schedule 课程清单
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, is it possible for you to finish all courses?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
- This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- There are several ways to represent a graph. For example, the input prerequisites is a graph represented by a list of edges. Is this graph representation appropriate?
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.
这道课程清单的问题对于我们学生来说应该不陌生,因为在选课的时候经常会遇到想选某一门课程,发现选它之前必须先上了哪些课程,这道题给了很多提示,第一条就告诉了这道题的本质就是在有向图中检测环。 LeetCode 中关于图的题很少,有向图的仅此一道,还有一道关于无向图的题是 Clone Graph。个人认为图这种数据结构相比于树啊,链表啊什么的要更为复杂一些,尤其是有向图,很麻烦。第二条提示是在讲如何来表示一个有向图,可以用边来表示,边是由两个端点组成的,用两个点来表示边。第三第四条提示揭示了此题有两种解法,DFS 和 BFS 都可以解此题。先来看 BFS 的解法,定义二维数组 graph 来表示这个有向图,一维数组 in 来表示每个顶点的入度。开始先根据输入来建立这个有向图,并将入度数组也初始化好。然后定义一个 queue 变量,将所有入度为0的点放入队列中,然后开始遍历队列,从 graph 里遍历其连接的点,每到达一个新节点,将其入度减一,如果此时该点入度为0,则放入队列末尾。直到遍历完队列中所有的值,若此时还有节点的入度不为0,则说明环存在,返回 false,反之则返回 true。代码如下:
解法一:
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> in(numCourses);
for (auto a : prerequisites) {
graph[a[]].push_back(a[]);
++in[a[]];
}
queue<int> q;
for (int i = ; i < numCourses; ++i) {
if (in[i] == ) q.push(i);
}
while (!q.empty()) {
int t = q.front(); q.pop();
for (auto a : graph[t]) {
--in[a];
if (in[a] == ) q.push(a);
}
}
for (int i = ; i < numCourses; ++i) {
if (in[i] != ) return false;
}
return true;
}
};
下面来看 DFS 的解法,也需要建立有向图,还是用二维数组来建立,和 BFS 不同的是,像现在需要一个一维数组 visit 来记录访问状态,这里有三种状态,0表示还未访问过,1表示已经访问了,-1 表示有冲突。大体思路是,先建立好有向图,然后从第一个门课开始,找其可构成哪门课,暂时将当前课程标记为已访问,然后对新得到的课程调用 DFS 递归,直到出现新的课程已经访问过了,则返回 false,没有冲突的话返回 true,然后把标记为已访问的课程改为未访问。代码如下:
解法二:
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>());
vector<int> visit(numCourses);
for (auto a : prerequisites) {
graph[a[]].push_back(a[]);
}
for (int i = ; i < numCourses; ++i) {
if (!canFinishDFS(graph, visit, i)) return false;
}
return true;
}
bool canFinishDFS(vector<vector<int>>& graph, vector<int>& visit, int i) {
if (visit[i] == -) return false;
if (visit[i] == ) return true;
visit[i] = -;
for (auto a : graph[i]) {
if (!canFinishDFS(graph, visit, a)) return false;
}
visit[i] = ;
return true;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/207
类似题目:
参考资料:
https://leetcode.com/problems/course-schedule/
https://leetcode.com/problems/course-schedule/discuss/58524/Java-DFS-and-BFS-solution
https://leetcode.com/problems/course-schedule/discuss/58516/Easy-BFS-Topological-sort-Java
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Course Schedule 课程清单的更多相关文章
- [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 prereq ...
- [LeetCode] 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 ...
- [LeetCode] Course Schedule III 课程清单之三
There are n different online courses numbered from 1 to n. Each course has some duration(course leng ...
- [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 ...
- [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 ...
- 【LeetCode】1462. 课程安排 IV Course Schedule IV (Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetcod ...
- LeetCode Course Schedule II
原题链接在这里:https://leetcode.com/problems/course-schedule-ii/ 题目: There are a total of n courses you hav ...
- [LeetCode] Course Schedule I (207) & II (210) 解题思路
207. Course Schedule There are a total of n courses you have to take, labeled from 0 to n - 1. Some ...
- LeetCode - Course Schedule 解题报告
以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...
随机推荐
- GeoServer中WMS、WFS的请求规范
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 1.1WMS简介 Web地图服务(WMS)利用具有地理空间位置 ...
- Spark的DataFrame的窗口函数使用
作者:Syn良子 出处:http://www.cnblogs.com/cssdongl 转载请注明出处 SparkSQL这块儿从1.4开始支持了很多的窗口分析函数,像row_number这些,平时写程 ...
- ASP.NET Core 中文文档 第三章 原理(10)依赖注入
原文:Dependency Injection 作者:Steve Smith 翻译:刘浩杨 校对:许登洋(Seay).高嵩 ASP.NET Core 的底层设计支持和使用依赖注入.ASP.NET Co ...
- go语言结构体
定义: 是一种聚合的数据类型,是由零个或多个任意类型的值聚合成的实体. 成员: 每个值称为结构体的成员. 示例: 用结构体的经典案例处理公司的员工信息,每个员工信息包含一个唯一的员工编号.员工的名字. ...
- iOS UITableViewableViewCell自适应高度
前两天做了一个项目,中间有遇到一个问题,就是聊天的时候cell高度的问题.这是一个很多前辈都遇到过,并且很完美的解决过的问题.这里主要是记录自己的学习心得.项目中首先想到的是用三方库,可是有问题,遂放 ...
- C#开发微信门户及应用(8)-微信门户应用管理系统功能介绍
最近对微信接口进行深入的研究,通过把底层接口一步步进行封装后,逐步升级到自动化配置.自动化应答,以及后台处理界面的优化和完善上,力求搭建一个较为完善.适用的微信门户应用管理系统. 微信门户应用管理系统 ...
- Servlet数据缓存
缓存是提高数据访问能力,降低服务器压力的一种必要的方式,今天我要说的数据缓存方式有两种,1-->session对单个数据访问接口页面的数据进行缓存,2-->单例模式对整个servlet页面 ...
- ECharts的简单使用过程
网页中经常要使用图表,以前使用的是highcharts插件,现在发现echarts使用起来和highcharts差不多,但是个人感觉echarts更酷炫,以下是echarts的使用过程,其实highc ...
- jQuery中的$.extend方法来扩展JSON对象及合并,方便调用对象方法
$.extend方法可以扩展JSON对象,用一个或多个其他对象来扩展一个对象,返回被扩展的对象. 例一 合并 settings 和 options,修改并返回 settings var setting ...
- CSS3之过渡及2D变换
transition过渡 transition-duration:; 运动时间 transition-delay:; 延迟时间 transition-timing-function:; 运动形式 ea ...