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]
.
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
题目大意:给一些课程列表,选修这些课程有先修课,就是A课程可能必须在上完B课程之后才能选,求一个合法的选修这些课的顺序,没有合法解的话返回空。
解题思路:
拓扑排序,可以用BFS的方式来做,首先每个课程都有一个入度,入度为0的作为最后选修的,然后把它依赖的课程的入度减一,依次递推到所有的课都选完。注意这个题数据比较大,不能用二维矩阵来存储图,只能用邻接表。
public class Solution { public int[] findOrder(int n, int[][] pre) { int[] res = new int[n]; int cnt=n-1; if(pre==null){ return new int[0]; } Map<Integer,Set<Integer>> adj = new HashMap<>(); int[] indegree = new int[n]; for(int i=0;i<pre.length;i++){ if(!adj.containsKey(pre[i][0])){ adj.put(pre[i][0],new HashSet<>()); } if(adj.get(pre[i][0]).add(pre[i][1])){ indegree[pre[i][1]]++; } } Deque<Integer> deque = new ArrayDeque<>(); for(int i=0;i<n;i++){ if(indegree[i]==0){ deque.offerLast(i); } } while(!deque.isEmpty()){ int key =deque.pollFirst(); res[cnt--] = key; if(adj.containsKey(key)){ for(int i:adj.get(key)){ if(--indegree[i]==0) deque.offerLast(i); } } } return cnt==-1?res:new int[0]; } }