course shedule(略)
2015-09-20 05:33
357 查看
There are a total of n courses you have to take, labeled from
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
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.
/article/1374768.html
0to
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.
public boolean canFinish(int numCourses, int[][] prerequisites) { int[][] matrix = new int[numCourses][numCourses]; // i -> j int[] indegree = new int[numCourses]; for (int i=0; i<prerequisites.length; i++) { int ready = prerequisites[i][0]; int pre = prerequisites[i][1]; if (matrix[pre][ready] == 0) indegree[ready]++; //duplicate case matrix[pre][ready] = 1; } int count = 0; Queue<Integer> queue = new LinkedList(); for (int i=0; i<indegree.length; i++) { if (indegree[i] == 0) queue.offer(i); } while (!queue.isEmpty()) { int course = queue.poll(); count++; for (int i=0; i<numCourses; i++) { if (matrix[course][i] != 0) { if (--indegree[i] == 0) queue.offer(i); } } } return count == numCourses; }
/article/1374768.html
相关文章推荐
- LeetCode (10): Regular Expression Matching [HARD]
- LeetCode Implement strStr()
- LeetCode Implement strStr()
- Ember.js 入门指南——{{action}} 助手
- Ember.js 入门指南——{{action}} 助手
- LeetCode "Move Zeroes"
- html标签认识的一些查漏补缺
- Mahout推荐的简单实现
- ajax提交数组
- 学习心得
- FMDB数据库
- 我现在对Git的认识
- office安装不了 “windows installer 服务不能更新一个或多个受保护的windows文件”
- FlushMode属性与transaction(spring注入的事务)
- 事务的特性..
- 我的感想
- IDEA 13、14 配合 gradle 时候无法正确编译资源文件的 bug
- 条款37:绝不重新定义继承而来的缺省参数值
- 分析Hibernate的事务处理机制
- 为什么hibernate需要事务?