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字符编码 ...
随机推荐
- 方案:抵御 不明SSL证书导致的 中间人攻击
基于SSL数字证书的中间人攻击已经不是一个新技术了,但是我发现很多人并不清楚这种威胁,甚至感觉无所谓,我相信他们是由于短暂的无知蒙蔽了双眼,希望这篇文章可以让更多的人知道这种攻击方式,并清除这种网络威 ...
- HashMap Java Doc
原文 public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneab ...
- Linux Java的环境变量搭建
JAVA JDK:http://www.oracle.com/technetwork/java/javase/downloads/index.html 下载完后,解压完并将其中的jdk文件夹移动到/u ...
- ps&&/proc/pid/xxx
ps 如果想看一个进程的启动时间,可以用lstart来看 [root@jiangyi02.sqa.zmf /home/ahao.mah] #ps -eo pid,lstart,etime,cmd |g ...
- 修改UITextField placeholder Color
[YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] ...
- Hopscotch(细节)
Hopscotch Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u Submit ...
- Eclipse代理设置
这段时间公司实行代理上网,不仅通过浏览器上网须要不停的输入username和password,在本地调试程序时候Eclipse居然也弹出框让输入username和password. 如图: 解决的方法 ...
- Java中遍历Map对象的方法
方法一: 在for-each循环中使用entries来遍历 这是最常见的遍历方式,在需要获取key和value时使用. Map<Integer, Integer> map = new Ha ...
- 前端JS模版库kino.razor - 原理流程分析 - 改进版轮子RazorJs
1.前言 从后台获取数据,在前端JS里面拼接字符串,不累吗?敢不敢找一款前端使使... 现在这种模板库比较多了,我用过的jquery-template .JsRender .听说过的一堆,还有各种MV ...
- 线程:Exchanger同步工具
可以在对中对元素进行配对和交换的线程的同步点,类似于交易,A拿着钱到达指定地点,B拿着物品到达指定地点,相互交换,然后各自忙各自的事去了. package ch03; import java.util ...