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.

解题思路一:

把每个节点放到图里,然后对每个节点进行BFS,如果出现自环,则为false,否则返回true,JAVA实现如下:

static public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites.length == 0 || prerequisites[0].length == 0)
return true;
HashMap<Integer, UndirectedGraphNode> hm = new HashMap<Integer, UndirectedGraphNode>();
for (int[] nums : prerequisites)
for (int i = 0; i < nums.length - 1; i++) {
if (!hm.containsKey(nums[i]))
hm.put(nums[i], new UndirectedGraphNode(nums[i]));
if (!hm.containsKey(nums[i + 1]))
hm.put(nums[i + 1], new UndirectedGraphNode(nums[i + 1]));
hm.get(nums[i]).neighbors.add(hm.get(nums[i + 1]));
}
Iterator<Integer> iterator = hm.keySet().iterator();
while (iterator.hasNext())
if (haveLoop(hm.get(iterator.next())))
return false;
return true;
} static boolean haveLoop(UndirectedGraphNode root) {
HashMap<UndirectedGraphNode, Boolean> hm = new HashMap<UndirectedGraphNode, Boolean>();
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
hm.put(root, true);
queue.add(root);
while (!queue.isEmpty()) {
UndirectedGraphNode temp = queue.poll();
for (UndirectedGraphNode temp2 : temp.neighbors) {
if (temp2 == root)
return true;
if (!hm.containsKey(temp2)) {
hm.put(temp2, true);
queue.add(temp2);
}
}
}
return false;
}

结果TLE,问题在于判断有向图是否有环的时候,对每一个节点判断其实浪费了很多时间%>_<%

解题思路二:

实际上,本题应该用拓扑排序判断图中是否有环,在储存边的时候,应该用set进行储存,具体内存请看考这篇博客:【LeetCode】Course Schedule 解题报告

JAVA传送门如下:

    public boolean canFinish(int numCourses, int[][] prerequisites) {
List<Set> posts = new ArrayList<Set>();
for (int i = 0; i < numCourses; i++)
posts.add(new HashSet<Integer>());
for (int i = 0; i < prerequisites.length; i++)
posts.get(prerequisites[i][1]).add(prerequisites[i][0]); // count the pre-courses
int[] preNums = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
Set set = posts.get(i);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]++;
}
} // remove a non-pre course each time
for (int i = 0; i < numCourses; i++) {
// find a non-pre course
int j = 0;
for ( ; j < numCourses; j++) {
if (preNums[j] == 0) break;
} // if not find a non-pre course
if (j == numCourses) return false; preNums[j] = -1; // decrease courses that post the course
Set set = posts.get(j);
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
preNums[it.next()]--;
}
} return true;
}

Java for LeetCode 207 Course Schedule【Medium】的更多相关文章

  1. Java for LeetCode 146 LRU Cache 【HARD】

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  2. Java for LeetCode 072 Edit Distance【HARD】

    Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2 ...

  3. Java for LeetCode 115 Distinct Subsequences【HARD】

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  4. Java for LeetCode 097 Interleaving String 【HARD】

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 ...

  5. LeetCode 31. Next Permutation【Medium】

    Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...

  6. Java for LeetCode 210 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 ...

  7. LeetCode:课程表II【210】

    LeetCode:课程表II[210] 题目描述 现在你总共有 n 门课需要选,记为 0 到 n-1. 在选修某些课程之前需要一些先修课程. 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一 ...

  8. LeetCode:累加数【306】

    LeetCode:累加数[306] 题目描述 累加数是一个字符串,组成它的数字可以形成累加序列. 一个有效的累加序列必须至少包含 3 个数.除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相 ...

  9. LeetCode:二进制手表【401】

    LeetCode:二进制手表[401] 题目描述 二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59). 每个 LED 代表一个 0 或 1,最低位在右 ...

随机推荐

  1. 弹出框二 之 bootbox.js

    1.可以通过Nuget下载 2.引入 jquery bootstrap bootbox.js 3.使用 $(function () { //bootbox.alert("确认删除" ...

  2. poj3254 Corn Fields (状压DP)

    http://poj.org/problem?id=3254 Corn Fields Time Limit: 2000MS   Memory Limit: 65536K Total Submissio ...

  3. 修改PUTTY支持保存密码

    1.从官网下载 Putty 0.60 Release 的 Windows 版源码 http://www.chiark.greenend.org.uk/~sgtatham/putty/download. ...

  4. Web渗透测试使用Kali Linux(一)渗透测试概要及环境部署

    渗透测试是利用已经发现的漏洞,采用恶意黑客的惯用手段来尝试对漏洞进行攻击. Kali Linux是BackTrack的进化版,是Linux的衍生版本,专门开发用作渗透测试,其中提供了很多的渗透测试工具 ...

  5. C#深入浅出 关键字(一)

    1.this this关键字用于指示当前对象“自己”,来看一个例子,了解什么时候需要用this class Star { String name; int age; public void SetIn ...

  6. PHP文件的上传与下载

    文件上传: 1.单个与多个文件上传 2.上传表单的属性设置 3.PHP配置文件中相关文件上传的设置 4.PHP处理上传的文件数据 php.ini配置: file_uploads = on; 默认on ...

  7. 如何在网页端启动WinForm 程序

    在逛淘宝或者使用QQ相关的产品的时候,比如淘宝我要联系店家点击旺旺图标的时候能够自动启动阿里旺旺进行聊天.之前很奇怪为什么网页端能够自动启动客户端程序,最近在开发吉特仓储管理系统的时候也遇到一个类似的 ...

  8. webpack 教程 那些事儿06-gulp+webpack多页

    本篇主要讲述用gulp+webpack构建多页应用 折腾到现在,项目还必须要进行,.vue文件必须要加载,也就是webpack必须引入.时间不多了,抛弃上个方案之后,只能牺牲热加载性能,用gulp+w ...

  9. 雪峰配置的nginx

  10. 跟着百度学PHP[4]OOP面对对象编程-4-对象成员的访问 ->

    使用一个减号一个尖括号->来达到访问对象成员. $object->方法 来看案例. <?php class Person{ private $name; "; var $s ...