现在你总共有 numCourses
门课需要选,记为 0
到 numCourses - 1
。给你一个数组 prerequisites
,其中 prerequisites[i] = [ai, bi]
,表示在选修课程 ai
前 必须 先选修 bi
。
- 例如,想要学习课程
0
,你需要先完成课程 1
,我们用一个匹配来表示:[0,1]
。
返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组 。
示例 1:
1 2 3
| 输入:numCourses = 2, prerequisites = [[1,0]] 输出:[0,1] 解释:总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。
|
示例 2:
1 2 3 4
| 输入:numCourses = 4, prerequisites = 输出: 解释:总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。 因此,一个正确的课程顺序是 。另一个正确的排序是 。
|
示例 3:
1 2
| 输入:numCourses = 1, prerequisites = 输出:
|
提示:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
- 所有
[ai, bi]
互不相同
拓扑排序
如果不能完成,即最终num != 0, 返回空
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] indegrees = new int[numCourses]; List<List<Integer>> adjacency = new ArrayList<>(); for(int i = 0; i < numCourses; i++){ adjacency.add(new ArrayList<>()); } for(int[] pre: prerequisites){ indegrees[pre[0]] ++; adjacency.get(pre[1]).add(pre[0]); } Deque<Integer> que = new ArrayDeque<>(); for(int i = 0; i < indegrees.length; i++){ if(indegrees[i] == 0){ que.add(i); } } int[] ans = new int[numCourses]; int k = 0; while(!que.isEmpty()){ int i = que.poll(); numCourses --; ans[k++] = i; List<Integer> join = adjacency.get(i); for(int next : join){ indegrees[next] --; if(indegrees[next] == 0){ que.offer(next); } } } return numCourses == 0 ? ans : new int[]{};
} }
|