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.

From: http://www.programcreek.com/2014/05/leetcode-course-schedule-java/

分析:

建立有向图,利用Toplogical sort逐一去掉没有father的节点。如果最后总的节点大于没有父节点的个数,表面里面有环。

 public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null) return true;
Map<Integer, Node> map = new HashMap<Integer, Node>(); for (int[] row : prerequisites) {
if (!map.containsKey(row[])) {
map.put(row[], new Node(row[], ));
} if (!map.containsKey(row[])) {
map.put(row[], new Node(row[], ));
} map.get(row[]).inDegree++;
map.get(row[]).list.add(map.get(row[]));
} Queue<Node> queue = new LinkedList<Node>();
for (Node node : map.values()) {
if (node.inDegree == ) {
queue.offer(node);
}
} while (!queue.isEmpty()) {
Node node = queue.poll();
for (Node child : node.list) {
child.inDegree--;
if (child.inDegree == ) {
queue.offer(child);
}
}
}
for (Node node : map.values()) {
if (node.inDegree != ) {
return false;
}
}
return true; }
} class Node {
int value;
int inDegree;
List<Node> list; public Node(int value, int inDegree) {
this.value = value;
this.inDegree = inDegree;
list = new ArrayList<Node>();
}
}

还有一种方法就是用dfs来看是否有back edge.

class Solution {
public static boolean hasCycle(List<List<Integer>> graph) {
// null input checks, etc int numNodes = graph.size();
boolean[] visited = new boolean[numNodes];
boolean[] current = new boolean[numNodes]; for (int i = ; i < numNodes; ++i) {
if (!visited[i]) {
boolean foundCycle = dfs(graph, visited, current, i);
if (foundCycle) {
return true;
}
}
} return false;
} private static boolean dfs(List<List<Integer>> graph, boolean[] visited, boolean[] current, int pos) {
if (current[pos]) {
return true;
}
if (visited[pos]) {
return false;
}
visited[pos] = true;
current[pos] = true; List<Integer> adj = graph.get(pos);
for (int dest : adj) {
boolean res = dfs(graph, visited, current, dest);
if (res) {
return true;
}
} current[pos] = false;
return false;
}
}

Course Schedule II

找出选课的顺序。

public class Solution {
public int[] findOrder(int n, int[][] prerequisites) {
if (prerequisites == null) return new int[];
Map<Integer, Node> map = new HashMap<Integer, Node>();
// very important
for (int i = ; i < n; i++){
map.put(i, new Node(i, ));
} for (int[] row : prerequisites) {
map.get(row[]).inDegree++;
map.get(row[]).list.add(map.get(row[]));
} List<Integer> list = new ArrayList<Integer>(); Queue<Node> queue = new LinkedList<Node>();
for (Node node : map.values()) {
if (node.inDegree == ) {
queue.offer(node);
}
} while (!queue.isEmpty()) {
Node node = queue.poll();
list.add(node.value);
for (Node child : node.list) {
child.inDegree--;
if (child.inDegree == ) {
queue.offer(child);
}
}
}
if (list.size() < n) return new int[];
int[] result = new int[list.size()];
for (int i = ; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
} class Node {
int value;
int inDegree;
List<Node> list; public Node(int value, int inDegree) {
this.value = value;
this.inDegree = inDegree;
list = new ArrayList<Node>();
}
}

Course Schedule I & II的更多相关文章

  1. [LeetCode] Course Schedule I (207) & II (210) 解题思路

    207. Course Schedule There are a total of n courses you have to take, labeled from 0 to n - 1. Some ...

  2. 【LeetCode】210. Course Schedule II

    Course Schedule II There are a total of n courses you have to take, labeled from 0 to n - 1. Some co ...

  3. [Leetcode Week4]Course Schedule II

    Course Schedule II题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/course-schedule-ii/description/ De ...

  4. 【刷题-LeetCode】210. Course Schedule II

    Course Schedule II There are a total of n courses you have to take, labeled from 0 to n-1. Some cour ...

  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. 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 Course Schedule II

    原题链接在这里:https://leetcode.com/problems/course-schedule-ii/ 题目: There are a total of n courses you hav ...

  8. FB面经prepare: task schedule II

    followup是tasks是无序的. 一开始是有序的,比如说1, 1, 2, 1,一定要先执行第一个task1,然后等task1恢复,再执行第2个task1,再执行task2..... follow ...

  9. Leetcode 210 Course Schedule II

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

随机推荐

  1. AuthenticationManager.SignOut() 无法注销用户的问题

    http://hadb.me/2015/03/23/authenticationmanager-signout-not-working/ 这文章不对, 我发现原因是不能有Response.Redire ...

  2. centos 7.0 编译安装mysql 5.6.22 再次总结 成功编译安装~ 越来越熟练了~

    查找php.ini文件所在位置 [root@localhost /]# find -name php.ini ./usr/etc/php/etc/php.ini mysql官网的安装说明http:// ...

  3. Joomla![1.5-3.4.5]反序列化远程代码执行EXP(直接写shell)

    Usage:x.py http://xxx.com # coding=utf-8# author:KuuKi# Help: joomla 1.5-3.4.5 unserialize remote co ...

  4. asp.net webform中使用async,await实现异步操作

    摘要 最近想着将项目中的部分耗时的操作,进行异步化.就自己弄个demo进行学习.只需下面几个步骤就可以将aspx页面中注册异步操作. demo 比如我们需要抓取某个url的内容,这个时候我们可能会有下 ...

  5. Cannot install NodeJs: /usr/bin/env: node: No such file or directory

    安装doxmate时,doxmate地址是:https://github.com/JacksonTian/doxmatenpm install doxmate -g 安装完后把错误:Cannot in ...

  6. Java实验1-文件IO

    目标:掌握Java类的创建,Java  I/O操作,Java集合类的使用等 内容: 王老师非常喜欢读书,为了便于查阅,他每次买书回家后就在笔记本上登记每本书的详细信息(书名.作者.出版社.出版日期.价 ...

  7. MYSQL 连接数据库命令收藏

    一.MySQL 连接本地数据库,用户名为“root”,密码“123”(注意:“-p”和“123” 之间不能有空格) C:\>mysql -h localhost -u root -p123 二. ...

  8. Mastering Web Application Development with AngularJS 读书笔记(二)

    第一章笔记 (二) 一.scopes的层级和事件系统(the eventing system) 在层级中管理的scopes可以被用做事件总线.AngularJS 允许我们去传播已经命名的事件用一种有效 ...

  9. sql拼音简写函数

    USE [HotelDB]GO /****** Object: UserDefinedFunction [dbo].[fn_GetPy] Script Date: 2016/1/4 13:29:13 ...

  10. [译]git status

    git status git status命令能展示工作目录和stage区的状态. 使用他你能看到那些修改被staged到了, 哪些没有, 哪些文件没有被Git tracked到. git statu ...