Course Schedule II 解答
2015-10-01 00:05
211 查看
Question
There are a total of n courses you have to take, labeled from0to
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, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
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 the correct course order is
[0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is
[0,1,2,3]. Another correct ordering is
[0,2,1,3].
Solution
Similar with "Course Schedule", the only difference is that we need to record path.Note: an empty array is the array with length = 0.
public class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { // This problem is to print one possible topological sort result // First, we need to construct a directed graph in the form of adjacency list List<Integer>[] adjacencyList = new ArrayList[numCourses]; int[] result = new int[numCourses]; int[] degree = new int[numCourses]; Arrays.fill(degree, 0); for (int j = 0; j < numCourses; j++) { List<Integer> tmpList = new ArrayList<Integer>(); tmpList.add(j); adjacencyList[j] = tmpList; } int length = prerequisites.length; for (int j = 0; j < length; j++) { int[] pair = prerequisites[j]; adjacencyList[pair[1]].add(pair[0]); degree[pair[0]]++; } // queue is to store nodes with 0 in-degree Queue<Integer> queue = new LinkedList<Integer>(); for (int j = 0; j < numCourses; j++) { if (degree[j] == 0) queue.add(j); } if (queue.size() == 0) return new int[0]; int i = 0; // begin bfs while (queue.size() > 0) { int current = queue.remove(); result[i] = current; List<Integer> currentList = adjacencyList[current]; for (int j = 1; j < currentList.size(); j++) { int tmp = currentList.get(j); degree[tmp]--; if (degree[tmp] == 0) queue.add(tmp); } i++; } if (i < numCourses) return new int[0]; return result; } }
相关文章推荐
- [pythontip]最大非连续子序列
- 欢迎使用CSDN-markdown编辑器
- Find them, Catch them
- 了解"DevOps"
- Java Swing编程:JTable表格
- LeetCode260——Single Number III精彩解法
- 《树的枚举》的理解
- 什么是块级元素和内联级元素
- Week 2 代码规范
- 从一路捞导航网(16lao.com)的UA控制的页面跳转的BUG说起
- Ubiquitous Religions
- 干货分享:国内冷链物流行业深度分析
- JS实现可调整倒计时间代码分享
- Android App支付系列(一):微信支付接入详细指南(附官方支付demo)
- php中preg_match的isU代表什么意思
- 基于OpenCart 开发支付宝,财付通,微信支付参数错误问题
- 详解JavaScript对Date对象的操作问题(生成一个倒数7天的数组)
- JS日期格式化之javascript Date format
- JS处理json日期格式化问题
- 基于OL2实现百度地图ABCD marker的效果