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. linux下awk命令详解

    简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...

  2. 3Sum Closest 解答

    Question Given an array S of n integers, find three integers in S such that the sum is closest to a ...

  3. Linux NFS服务器搭建

    1.NFS:NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机之间通过TCP/IP网络共享资源.   在NFS的应用中,本地N ...

  4. pyqt columnView例子学习

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' from PyQt4.QtGui import  * from Py ...

  5. mysql-error --(ERROR 1135 (HY000): Can't create a new thread (errno 11); if you are not out)

    报错信息: ERROR 1135 (HY000): Can't create a new thread (errno 11); if you are not out 解决办法: # 查看限制情况 [r ...

  6. XTU OJ 1209 Alice and Bob 2014(嘉杰信息杯ACM/ICPC湖南程序设计邀请赛暨第六届湘潭市程序设计竞赛)

    Problem Description The famous "Alice and Bob" are playing a game again. So now comes the ...

  7. [转]轻量级 Java Web 框架架构设计

    工作闲暇之余,我想设计并开发一款轻量级 Java Web 框架,看看能否取代目前最为流行的而又越来越重的 Spring.Hibernate 等框架.请原谅在下的大胆行为与不自量力,本人不是为了重造轮子 ...

  8. JavaScript ----------------- 原型式继承

    思想:借助原型可以基于已有的对象创建新对象,同时还不必因此创建自定义类型.为了达到这个目的,看看下面的实现方式 function object(o){ function F(){ } F.protot ...

  9. tomcat6.0目录和server.xml详解

    Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,目前最新版本是6.x,相对5.x性能提升很多,主要优化了内存使用,增强IO能力,重新构造集群功能. 近期对Tomcat6.x作深入学习, ...

  10. 练习使用jquery.并将验证强度的功能加到注册页面中