标签:
和207 Course Schedule是一样的
1 public int[] findOrder(int numCourses, int[][] prerequisites) { 2 int[] result = new int[numCourses]; 3 if(numCourses < 1) { 4 return new int[0]; 5 } 6 int index = numCourses - 1; 7 Queue<Integer> queue = new LinkedList<Integer>(); 8 int[] indegree = new int[numCourses]; 9 int len = prerequisites.length; 10 for(int i = 0; i < len; i++) { 11 indegree[prerequisites[i][1]]++; 12 } 13 for(int i = 0; i < numCourses; i++) { 14 if(indegree[i] == 0) { 15 queue.offer(i); 16 } 17 } 18 while(!queue.isEmpty()) { 19 int cur = queue.poll(); 20 result[index] = cur; 21 index--; 22 for(int i = 0; i < len; i++) { 23 if(prerequisites[i][0] == cur) { 24 indegree[prerequisites[i][1]]--; 25 if(indegree[prerequisites[i][1]] == 0) { 26 queue.add(prerequisites[i][1]); 27 } 28 } 29 } 30 } 31 for(int i = 0; i < numCourses; i++) { 32 if(indegree[i] != 0) { 33 return new int[0]; 34 } 35 } 36 return result; 37 }
标签:
原文地址:http://www.cnblogs.com/warmland/p/5693759.html