题目链接:https://leetcode.com/problems/course-schedule-ii/
题目:
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].
思路:
跟上题解法一样,只是增加了在过程中记录结果,这一步骤。
算法:
public int[] findOrder(int numCourses, int[][] prerequisites) {
int preCount[] = new int[numCourses];
Queue<Integer> notPre = new LinkedList<Integer>();
int res[] = new int[numCourses];
int num = -1;// 可以拓扑排序的节点个数
// 统计每个结点作为前驱的次数
for (int i = 0; i < prerequisites.length; i++) {
preCount[prerequisites[i][0]]++;
}
// 记录出度为0的结点
for (int i = 0; i < preCount.length; i++) {
if (preCount[i] == 0) {
notPre.offer(i);
num++;
res[num] = i;
}
}
while (!notPre.isEmpty()) {// BFS
int node = notPre.poll();
for (int i = 0; i < prerequisites.length; i++) {
if (prerequisites[i][1] == node) {
preCount[prerequisites[i][0]]--;// 删除和node有关的边
if (preCount[prerequisites[i][0]] == 0) {// 如果出度为0
num++;
res[num] = prerequisites[i][0];
notPre.offer(prerequisites[i][0]);
}
}
}
}
return (num+1) == numCourses ? res : new int[0];
}

本文针对LeetCode上的课程安排II问题,详细解析了如何使用拓扑排序算法来找出完成所有课程的一种可能顺序。文章通过具体的例子说明了算法的实现过程,并提供了完整的Java代码实现。

1144

被折叠的 条评论
为什么被折叠?



