Course Schedule II 解答
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, 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;
}
}
最新文章
- Security Tools (Contain CTF tools)
- Linux 服务器的网络配置 - 2. 查看 Linux 服务器的进程
- 使用NSKeyedArchiver归档
- rm 删除带空格的文件或者目录
- android中两种方式打开网页
- chrome 网络面板
- UI:这段时间的小总结
- Java基础知识强化之集合框架笔记75:哈希表
- JAVA_build_ant_sed
- 文件系统 busybox and initramfs
- Haskell 几乎无疼痛入门指南
- spring在扫描包中的注解类时出现Failed to read candidate component错误
- UVA1213
- react native 左边固定,右边横向滑动左右自适应高度
- Android完全退出应用的方法
- Ubuntu18.04提示wifi无法连接
- Curl中的参数知多少
- 【Oracle】【5】主键、外键管理
- Centos7下python3安装pip-9.0.1
- 使用Python中的HTMLParser、cookielib抓取和解析网页、从HTML文档中提取链接、图像、文本、Cookies(二)(转)