public class Solution { //test case [1,0] public int[] findOrder(int numCourses, int[][] prerequisites) { int[] map = new int[numCourses]; int n = prerequisites.length; int[] res = new int[numCourses]; for(int i=0; i<n; i++) { map[ prerequisites[i][1] ] ++; } Queue<Integer> que = new LinkedList<Integer>(); int index = numCourses-1; for(int i=0; i<numCourses; i++) { if(map[i] == 0) { que.add(i); res[index--] = i; } } while(!que.isEmpty() ){ int k = que.remove(); for(int i=0; i<n; i++) { int l = prerequisites[i][1]; if(k==prerequisites[i][0]) { map[l]--; if(map[l] == 0) { que.add(l); res[index--] = l; } } } } if(index!=-1) return new int[0]; else return res; } }
补充一个python的实现,使用深度优先遍历,进行拓扑排序:
1 class Solution: 2 def dfs(self,visited,memo,dic,i,postCourse): 3 if visited[i]: 4 return True 5 if memo[i] == 0: 6 return False 7 elif memo[i] == 1: 8 return True 9 for cs in dic[i]: 10 visited[i] = True 11 bl = self.dfs(visited,memo,dic,cs,postCourse) 12 visited[i] = False 13 if bl: 14 memo[i] = 1 15 return True 16 memo[i] = 0 17 postCourse.append(i) 18 return False 19 def findOrder(self, numCourses: int, prerequisites: 'List[List[int]]') -> 'List[int]': 20 dic = {} 21 n = len(prerequisites) 22 for i in range(numCourses): 23 dic[i] = [] 24 for i in range(n): 25 cs = prerequisites[i][0]#当前课程 26 pre = prerequisites[i][1]#前置课程 27 dic[cs].append(pre) 28 visited = [False for _ in range(numCourses)] 29 memo = [-1 for _ in range(numCourses)] 30 postCourse = [] 31 for i in range(numCourses): 32 if self.dfs(visited,memo,dic,i,postCourse): 33 return [] 34 return postCourse