Course Schedule 解答
Question
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.
Solution 1 -- DFS
This question can be transferred to judge whether the graph has cycle.
There are two key points for this question.
1. How to construct adjacency list according to edge lists? (Graph representation)
Usually, we use ArrayList[] to represent adjacency list.
2. How to use DFS to judge whether the graph has cycle. This solution can be further modified to implement topological sort.
Time complexity O(|V| + |E|)
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null || prerequisites.length == 0)
return true;
// Construct adjacency list
ArrayList<Integer>[] adjacencyList = new ArrayList[numCourses];
for (int i = 0; i < numCourses; i++) {
ArrayList<Integer> tmpList = new ArrayList<Integer>();
tmpList.add(i);
adjacencyList[i] = tmpList;
}
for (int i = 0; i < prerequisites.length; i++) {
int[] currentPair = prerequisites[i];
adjacencyList[currentPair[0]].add(currentPair[1]);
} // DFS Because we need to judge whether the graph has cycle, we use three status for each node
// 0 -> not start; 1 -> start dfs, but not complete; 2 -> complete dfs;
short[] used = new short[numCourses];
for (int i = 0; i < numCourses; i++) {
if (used[i] == 0) {
boolean result = dfs(adjacencyList, used, i);
if (!result)
return false;
}
}
return true;
} private boolean dfs(ArrayList<Integer>[] graph, short[] used, int i) {
used[i] = 1;
ArrayList<Integer> neighbor = graph[i];
for (int j = 1; j < neighbor.size(); j++) {
int index = neighbor.get(j);
if (used[index] == 1)
return false;
if (used[index] == 2)
continue;
if (used[index] == 0) {
if (!dfs(graph, used, index))
return false;
}
}
used[i] = 2;
return true;
} }
Solution 2
We adopt second way to implement topological sort.
We maintain a queue to store vertices whose in-degree is 0. Time complexity O(|V| + |E|).
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null || prerequisites.length == 0)
return true;
// Construct adjacency list
ArrayList<Integer>[] adjacencyList = new ArrayList[numCourses];
for (int i = 0; i < numCourses; i++) {
ArrayList<Integer> tmpList = new ArrayList<Integer>();
tmpList.add(i);
adjacencyList[i] = tmpList;
}
for (int i = 0; i < prerequisites.length; i++) {
int[] currentPair = prerequisites[i];
adjacencyList[currentPair[0]].add(currentPair[1]);
}
// Maintain a queue to store vertices with in-degree is 0
Queue<Integer> queue = new LinkedList<Integer>();
int[] inDegree = new int[numCourses];
Arrays.fill(inDegree, 0);
// Initialize in-degree array
for (ArrayList<Integer> tmpList : adjacencyList) {
int size = tmpList.size();
for (int i = 1; i < size; i++)
inDegree[tmpList.get(i)]++;
}
// Initialize queue
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0)
queue.add(i);
}
if (queue.size() == 0)
return false;
int count = 0;
while (queue.size() > 0) {
int key = queue.remove();
ArrayList<Integer> neighbor = adjacencyList[key];
for (int i = 1; i < neighbor.size(); i++) {
int tmp = neighbor.get(i);
inDegree[tmp]--;
if (inDegree[tmp] == 0) {
queue.add(tmp);
}
}
count++;
}
return count == numCourses;
}
}
Course Schedule 解答的更多相关文章
- Course Schedule II 解答
Question There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may ...
- LeetCode算法题目解答汇总(转自四火的唠叨)
LeetCode算法题目解答汇总 本文转自<四火的唠叨> 只要不是特别忙或者特别不方便,最近一直保持着每天做几道算法题的规律,到后来随着难度的增加,每天做的题目越来越少.我的初衷就是练习, ...
- Python3.7.1学习(二)使用schedule模块定时执行任务
python中有一个轻量级的定时任务调度的库:schedule.他可以完成每分钟,每小时,每天,周几,特定日期的定时任务.因此十分方便我们执行一些轻量级的定时任务. 1 安装 1.1在cmd中输入p ...
- Handler的源码和常见问题的解答不崩溃
Handler是Android中的消息处理机制,是一种线程间通信的解决方案,同时你也可以理解为它天然的为我们在主线程创建一个队列,队列中的消息顺序就是我们设置的延迟的时间,如果你想在Android中实 ...
- [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 课程清单
There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...
- 精选30道Java笔试题解答
转自:http://www.cnblogs.com/lanxuezaipiao/p/3371224.html 都 是一些非常非常基础的题,是我最近参加各大IT公司笔试后靠记忆记下来的,经过整理献给与我 ...
- 精通Web Analytics 2.0 (8) 第六章:使用定性数据解答”为什么“的谜团
精通Web Analytics 2.0 : 用户中心科学与在线统计艺术 第六章:使用定性数据解答"为什么"的谜团 当我走进一家超市,我不希望员工会认出我或重新为我布置商店. 然而, ...
- 【字符编码】Java字符编码详细解答及问题探讨
一.前言 继上一篇写完字节编码内容后,现在分析在Java中各字符编码的问题,并且由这个问题,也引出了一个更有意思的问题,笔者也还没有找到这个问题的答案.也希望各位园友指点指点. 二.Java字符编码 ...
随机推荐
- POJ_Fibonacci POJ_3070(矩阵快速幂入门题,附上自己写的矩阵模板)
Fibonacci Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 10521 Accepted: 7477 Descri ...
- 【HDU1879】继续畅通工程(MST基础题)
真心大水题...不多说. #include <iostream> #include <cstring> #include <cstdlib> #include &l ...
- C 本地文件夸网文件Cp操作
1,linux平台C简单实现本地文件cp 码子及运行效果测试
- javascript运算符整理
说起运算符,基本上各类编程语言中都会涉及,使用方法大同小异.今天在这里以javascript做简单的整理. 总得来说运算符还是比较的多,大致可以分为以下几种类型: 一元运算符 位运算符 布尔运算符 乘 ...
- ping不通的几种可能原因
平时使用中常常会碰到ping不通的情况,ping不通的原因有非常多,比方路由设置问题,比方网络问题,下面列出几点原因: 1.太心急.即网线刚插到交换机上就想Ping通网关,忽略了生成树的收敛 ...
- mysql 数据库连接池
hibernate配置C3P0详解 分类: hibernate 2013-08-14 16:16 1213人阅读 评论 ...
- iOS nav加角标
写一个类别加上就可以啦 #import "UIBarButtonItem+Badge.h" #import "BadgeView.h" #import < ...
- 最大流EK算法模板
最近学了下最大流算法,大概思想算是懵懵懂懂了,现在想把模板记录下来,以备后面深刻学习之用. #include<cstdio> #include<cstring> using n ...
- C++ Primer Chapter 1
When I start reviewing, I thought Chapter is useless. Because the title is "Getting Start" ...
- C++ 语言特性的性能分析
转载:http://www.cnblogs.com/rollenholt/archive/2012/05/07/2487244.html 大多数开发人员通常都有这个观点,即汇编语言和 C 语 ...