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 解答的更多相关文章

  1. Course Schedule II 解答

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

  2. LeetCode算法题目解答汇总(转自四火的唠叨)

    LeetCode算法题目解答汇总 本文转自<四火的唠叨> 只要不是特别忙或者特别不方便,最近一直保持着每天做几道算法题的规律,到后来随着难度的增加,每天做的题目越来越少.我的初衷就是练习, ...

  3. Python3.7.1学习(二)使用schedule模块定时执行任务

    python中有一个轻量级的定时任务调度的库:schedule.他可以完成每分钟,每小时,每天,周几,特定日期的定时任务.因此十分方便我们执行一些轻量级的定时任务. 1 安装  1.1在cmd中输入p ...

  4. Handler的源码和常见问题的解答不崩溃

    Handler是Android中的消息处理机制,是一种线程间通信的解决方案,同时你也可以理解为它天然的为我们在主线程创建一个队列,队列中的消息顺序就是我们设置的延迟的时间,如果你想在Android中实 ...

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

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

  7. 精选30道Java笔试题解答

    转自:http://www.cnblogs.com/lanxuezaipiao/p/3371224.html 都 是一些非常非常基础的题,是我最近参加各大IT公司笔试后靠记忆记下来的,经过整理献给与我 ...

  8. 精通Web Analytics 2.0 (8) 第六章:使用定性数据解答”为什么“的谜团

    精通Web Analytics 2.0 : 用户中心科学与在线统计艺术 第六章:使用定性数据解答"为什么"的谜团 当我走进一家超市,我不希望员工会认出我或重新为我布置商店. 然而, ...

  9. 【字符编码】Java字符编码详细解答及问题探讨

    一.前言 继上一篇写完字节编码内容后,现在分析在Java中各字符编码的问题,并且由这个问题,也引出了一个更有意思的问题,笔者也还没有找到这个问题的答案.也希望各位园友指点指点. 二.Java字符编码 ...

随机推荐

  1. 脚本控制向Android模拟拨打电话,发送短信,定位设置功能

    做行为触发的时候要向模拟器实现拨打电话,发送短信,定位设置的的功能,可以很方便通过telnet localhost  5554实现. 写个脚本很快的搞定了.网上资料很多,脚本的很少,也所积点德啦. 写 ...

  2. Jndi and c3p0 in Tomcat

    Tomcat 中Jndi是使用Tomcat自带的连接池抛弃Tomcat自带的连接池.使用c3p0 . 环境:Tomcat 5.5.20下面配置只适合Tomcat 5.5.X 下面来看Jndi 与 c3 ...

  3. Chosen 基本使用

    点击下载Chosen 引入文件 chosen.css jquery-1.7.1.min.js chosen.jquery.js 绑定数据: for (var i = 0; i < data.le ...

  4. cStringIO模块例子

    # Vorbis comment support for Mutagen # Copyright 2005-2006 Joe Wreschnig # # This program is free so ...

  5. 苹果拒绝App内部使用版本检测功能

    10.6 - Apple and our customers place a high value on simple, refined, creative, well thought through ...

  6. Tcp通讯协议

    了解了Udp通讯协议之后,我们再认识一个常用的通讯协议:Tcp Tcp传输特点: --依赖于Socket和ServerSocket对象 --建立客户端和服务端 --建立连接后,通过Socket中的 I ...

  7. Java客户端Jedis的八种调用方式

      redis是一个著名的key-value存储系统,而作为其官方推荐的java版客户端jedis也非常强大和稳定,支持事务.管道及有jedis自身实现的分布式. 在这里对jedis关于事务.管道和分 ...

  8. MongoDB 数据库安装

    首先在官网上下载数据库:官网上提供了两种形式的数据库,一种是免安装版的,一种是安装版的.这点跟apache的tomcat类似,安装版的有可视化的界面对服务进行启动和关闭,可是还是比較喜欢免安装的.不解 ...

  9. MFC读写配置文件

    void CFileTextDoc::OnIniread() { // TODO: Add your command handler code here CString strStudName;   ...

  10. jquery 根据网站url给导航nav添加active效果

    后台的同事因为把nav公用了,所以无法单页添加active,一下方法通过判断url的后缀给当前页添加active $(function(){ var _nava= $('.nav .nav-wrapp ...