[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 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.
- 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.
给定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 课程安排的更多相关文章
- [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 ...
- LN : leetcode 207 Course Schedule
lc 207 Course Schedule 207 Course Schedule There are a total of n courses you have to take, labeled ...
- LeetCode - 207. Course Schedule
207. Course Schedule Problem's Link ---------------------------------------------------------------- ...
- 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 ...
- [LeetCode] 207. Course Schedule 课程表
题目: 分析: 这是一道典型的拓扑排序问题.那么何为拓扑排序? 拓扑排序: 有三件事情A,B,C要完成,A随时可以完成,但B和C只有A完成之后才可完成,那么拓扑排序可以为A>B>C或A&g ...
- [leetcode]207. Course Schedule课程表
在一个有向图中,每次找到一个没有前驱节点的节点(也就是入度为0的节点),然后把它指向其他节点的边都去掉,重复这个过程(BFS),直到所有节点已被找到,或者没有符合条件的节点(如果图中有环存在). /* ...
- (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 ...
- 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 ...
- 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 ...
随机推荐
- Unity进阶之ET网络游戏开发框架 07-修正游客登录的异步BUG
版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...
- 第一次使用Git(常用的dos命令整理)
在使用git的过程中,有许多dos命令也要会用才行 Git 工具分类 命令行 bash.cmd.power shell GUI Git GUI.GitHub Desktop IDE 集成 Visual ...
- Linux 设置系统编码
1.locale -a查看系统支持的语言2.进入etc/sysconfig/3.编辑i18n4.修改lang 5.设置完成后刷新:i18n source /etc/sysconfig/i18n
- Codeforces C. Maximum Value(枚举二分)
题目描述: Maximum Value time limit per test 1 second memory limit per test 256 megabytes input standard ...
- 51nod 2502 最多分成多少块
小b有个长度为n的数组a,她想将这个数组排序. 然而小b很懒,她觉得对整个数组排序太累了,因此她请你将a分成一些块,使得她只需要对每一块分别排序,就能将整个数组排序. 请问你最多能把a分成多少块. 保 ...
- gson之将对象转化成json字符串的方法
public class GsonUtil { /** * 将object对象转成json格式字符串 */ public static String toJson(Object object) { G ...
- HBase应用
太多column family的影响 每个 MemoryStore分配到的内存较少,进而导致过多的合并,影响性能 几个column family比较合适呢 推荐是:1-3个 划分column fa ...
- [VSCode] Adding Custom Syntax Highlighting to a Theme in VSCode
VSCode Themes are a quick way to update the color scheme and syntax highlighting of your code, but y ...
- LeetCode 787. Cheapest Flights Within K Stops
原题链接在这里:https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题目: There are n cities connec ...
- 二八法则(The 80/20 Principle)
二八法则的定义:在任何一组事物中,最重要的只占其中一小部分,约20%,其余80%尽管占多数,却是次要的. 二八法则的例子:社会上20%的人占有80%的社会财富 20%的工厂有80%的产出 80%的利润 ...