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?

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 it is possible.

2, [[1,0],[0,1]]

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.

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

给定n个课程,上课的顺序有先后要求,用pair表示,判断是否能完成所有课程。

对于每一对课程的顺序关系,把它看做是一个有向边,边是由两个端点组成的,用两个点来表示边,所有的课程关系即构成一个有向图,问题相当于判断有向图中是否有环。判断有向图是否有环的方法是拓扑排序。

拓扑排序:维护一张表记录所有点的入度,移出入度为0的点并更新其他点的入度,重复此过程直到没有点的入度为0。如果原有向图有环的话,此时会有剩余的点且其入度不为0;否则没有剩余的点。

图的拓扑排序可以DFS或者BFS。遍历所有边,计算点的入度;将入度为0的点移出点集,并更新剩余点的入度;重复步骤2,直至没有剩余点或剩余点的入度均大于0。

这里不能使用邻接矩阵,应该使用邻接表来存储有向图的信息。邻接表可以使用结构体来实现,每个结构体存储一个值以及一个指向下一个节点的指针,同时维护一个存储多个头结点的数组即可。除此之外,在数据结构简单的情况下,还可以使用数组来模拟简单的邻接表。

Java:BFS

public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] pre = new int[numCourses];
List<Integer>[] satisfies = new List[numCourses];
for(int i=0; i<numCourses; i++) satisfies[i] = new ArrayList<>();
for(int i=0; i<prerequisites.length; i++) {
satisfies[prerequisites[i][1]].add(prerequisites[i][0]);
pre[prerequisites[i][0]] ++;
}
int finish = 0;
LinkedList<Integer> queue = new LinkedList<>();
for(int i=0; i<numCourses; i++) {
if (pre[i] == 0) queue.add(i);
}
while (!queue.isEmpty()) {
int course = queue.remove();
finish ++;
if (satisfies[course] == null) continue;
for(int c: satisfies[course]) {
pre[c] --;
if (pre[c] == 0) queue.add(c);
}
}
return finish == numCourses;
}
}

Java:DFS

public class Solution {
private boolean[] canFinish;
private boolean[] visited;
private List<Integer>[] depends;
private boolean canFinish(int course) {
if (visited[course]) return canFinish[course];
visited[course] = true;
for(int c: depends[course]) {
if (!canFinish(c)) return false;
}
canFinish[course] = true;
return canFinish[course];
}
public boolean canFinish(int numCourses, int[][] prerequisites) {
canFinish = new boolean[numCourses];
visited = new boolean[numCourses];
depends = new List[numCourses];
for(int i=0; i<numCourses; i++) depends[i] = new ArrayList<Integer>();
for(int i=0; i<prerequisites.length; i++) {
depends[prerequisites[i][0]].add(prerequisites[i][1]);
}
for(int i=0; i<numCourses; i++) {
if (!canFinish(i)) return false;
}
return true;
}
}

Python:

import collections

class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
zero_in_degree_queue, in_degree, out_degree = collections.deque(), {}, {} for i, j in prerequisites:
if i not in in_degree:
in_degree[i] = set()
if j not in out_degree:
out_degree[j] = set()
in_degree[i].add(j)
out_degree[j].add(i) for i in xrange(numCourses):
if i not in in_degree:
zero_in_degree_queue.append(i) while zero_in_degree_queue:
prerequisite = zero_in_degree_queue.popleft() if prerequisite in out_degree:
for course in out_degree[prerequisite]:
in_degree[course].discard(prerequisite)
if not in_degree[course]:
zero_in_degree_queue.append(course) del out_degree[prerequisite] if out_degree:
return False return True

C++: BFS

class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int> > graph(numCourses, vector<int>(0));
vector<int> in(numCourses, 0);
for (auto a : prerequisites) {
graph[a[1]].push_back(a[0]);
++in[a[0]];
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (in[i] == 0) q.push(i);
}
while (!q.empty()) {
int t = q.front();
q.pop();
for (auto a : graph[t]) {
--in[a];
if (in[a] == 0) q.push(a);
}
}
for (int i = 0; i < numCourses; ++i) {
if (in[i] != 0) return false;
}
return true;
}
};

C++: DFS

class Solution {
public:
bool canFinish(int numCourses, vector<vector<int> >& prerequisites) {
vector<vector<int> > graph(numCourses, vector<int>(0));
vector<int> visit(numCourses, 0);
for (auto a : prerequisites) {
graph[a[1]].push_back(a[0]);
}
for (int i = 0; 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] == -1) return false;
if (visit[i] == 1) return true;
visit[i] = -1;
for (auto a : graph[i]) {
if (!canFinishDFS(graph, visit, a)) return false;
}
visit[i] = 1;
return true;
}
};

类似题目:

[LeetCode] 210. Course Schedule II 课程安排II  

  

All LeetCode Questions List 题目汇总

[LeetCode] 207. Course Schedule 课程安排的更多相关文章

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

  2. LN : leetcode 207 Course Schedule

    lc 207 Course Schedule 207 Course Schedule There are a total of n courses you have to take, labeled ...

  3. LeetCode - 207. Course Schedule

    207. Course Schedule Problem's Link ---------------------------------------------------------------- ...

  4. Java for LeetCode 207 Course Schedule【Medium】

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  5. [LeetCode] 207. Course Schedule 课程表

    题目: 分析: 这是一道典型的拓扑排序问题.那么何为拓扑排序? 拓扑排序: 有三件事情A,B,C要完成,A随时可以完成,但B和C只有A完成之后才可完成,那么拓扑排序可以为A>B>C或A&g ...

  6. [leetcode]207. Course Schedule课程表

    在一个有向图中,每次找到一个没有前驱节点的节点(也就是入度为0的节点),然后把它指向其他节点的边都去掉,重复这个过程(BFS),直到所有节点已被找到,或者没有符合条件的节点(如果图中有环存在). /* ...

  7. (medium)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 ...

  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 p ...

  9. 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 ...

随机推荐

  1. PAT甲级1003题解——Dijkstra

    解题步骤: 1.初始化:设置mat[][]存放点之间的距离,vis[]存放点的选取情况,people[]存放初始时每个城市的人数,man[]存放到达每个城市的救援队的最多的人数,num[]存放到达每个 ...

  2. Kotlin注解深入解析与实例剖析

    在上一次https://www.cnblogs.com/webor2006/p/11522798.html中学习了Kotlin注解相关的东东,这次继续对Kotlin的注解继续学习: 注解也可以拥有自己 ...

  3. 解决Invalid character found in the request target. The valid characters are defined in RFC 7230 and RF

    通过这里的回答,我们可以知道: Tomcat在 7.0.73, 8.0.39, 8.5.7 版本后,添加了对于http头的验证. 具体来说,就是添加了些规则去限制HTTP头的规范性 参考这里 具体来说 ...

  4. Top 20 IoT Platforms in 2018

    https://internetofthingswiki.com/top-20-iot-platforms/634/ After learning what is the internet of th ...

  5. c#中的多态学习总结

    c#的多台方法,大体上和c++的类似,但是有点区别的,我这里刚刚初学,因此把重点记录下. 多态是同一个行为具有多个不同表现形式或形态的能力. 多态性意味着有多重形式.在面向对象编程范式中,多态性往往表 ...

  6. Mybatis框架-@Param注解

    回顾一下上一个小demo中存在的问题,是是根据用户的id修改用户的密码,我们只是修改了用户的密码,结果我们的在写接口方法的时候掺入的参数确实一个User对象,这样让别人看到我们的代码真的是很难读懂啊! ...

  7. python zlib模块缺失报错:RuntimeError: Compression requires the (missing) zlib module

    解决方式: # yum install zlib # yum install zlib-devel 下载成功后,进入python2.7的目录,重新执行 #make #make install 此时先前 ...

  8. H5中实现加载更多的逻辑及代码执行。

    H5中加载更多的逻辑总结: 1.首先,需要三个底部的提示,分别是“加载中”.“--我是有底线的--”.“暂时没有记录”,当然,这三句话根据不同的项目,可以自定义.具体代码例子如下: <div c ...

  9. 2019.12.10 定义数组及java内存划分

    //数据类型[ ] 数组名 = new 数据类型[元素个数或数组长度]; int[] x = new int[100]; //类型[] 数组名 = new 类型[]{元素,元素,……}; String ...

  10. 洛谷 P3183 [HAOI2016]食物链 题解

    P3183 [HAOI2016]食物链 题目描述 如图所示为某生态系统的食物网示意图,据图回答第1小题现在给你n个物种和m条能量流动关系,求其中的食物链条数.物种的名称为从1到n编号M条能量流动关系形 ...