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. PHP里关于时间日期大小写(Y,y,M,m...)

    y代表年份,取后两位        Y代表年份全部        m代表月份        M代表月份英文简写        d代表天        D代表星期几的简写        h代表小时,12 ...

  2. C#实现下载功能,可用于软件自动更新

    以前在百度写的文档,转移到此处 软件截图: 代码下载: http://twzy.ys168.com/   在代码下载文件夹中 //代码: using System; using System.Comp ...

  3. What is NetApp's Cluster File System?

    Data ONTAP GX: A Scalable Storage Cluster www.usenix.org/event/fast07/tech/full_papers/eisler/eisler ...

  4. kaggle之泰坦尼克的沉没

    Titanic 沉没 参见:https://github.com/lijingpeng/kaggle 这是一个分类任务,特征包含离散特征和连续特征,数据如下:Kaggle地址.目标是根据数据特征预测一 ...

  5. [Python笔记][第四章Python正则表达式]

    2016/1/28学习内容 第四章 Python字符串与正则表达式之正则表达式 正则表达式是字符串处理的有力工具和技术,正则表达式使用预定义的特定模式去匹配一类具有共同特征的字符串,主要用于字符串处理 ...

  6. ASP.NET开发学习视频教程大全(共800集)

    ASP.NET是微软.NET平台的支柱之一,被广泛应用在WEB等互联网开发领域,因此它的强大性和适应性,可以使它运行在Web应用软件开发者的几乎全部的平台上.这里整理了最全的ASP.NET开发学习视频 ...

  7. T4运行时模板

    可以通过Visual Studio运行时文本模板在您的应用程序在运行时生成文本字符串. 执行应用程序的计算机不必具有 Visual Studio. 运行库模板有时称为"预处理文本模板&quo ...

  8. 上传图片预览,支持IE6

    //说明:图片上传预览插件 //上传的时候可以生成固定宽高范围内的等比例缩放图 //参数设置: //width 存放图片固定大小容器的宽 //height 存放图片固定大小容器的高 //imgDiv ...

  9. Funsion Charts 学习(二)

    下载FusionCharts 3.1网址为 http://www.onlinedown.net/soft/92224.htm 第一个demo 新建一个文件夹,命名为demo 在文件夹中新建一个两个文件 ...

  10. CDZSC_2015寒假新人(2)——数学 C

    C - C Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Status ...