LeetCode-Course Schedule II

LiBlog發表於2016-08-30

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.

Solution:

 1 public class Solution {
 2     public int[] findOrder(int numCourses, int[][] prerequisites) {
 3         if (numCourses ==0)
 4             return new int[0];
 5 
 6         int[] preNum = new int[numCourses];
 7         List<List<Integer>> childMap = new ArrayList<List<Integer>>();
 8         for (int i=0;i<numCourses;i++){
 9             childMap.add(new ArrayList<Integer>());
10         }
11         
12         for (int[] pair : prerequisites) {
13             int course1 = pair[0], course2 = pair[1];
14             preNum[course1]++;
15             childMap.get(course2).add(course1);
16         }
17 
18         // Get init list
19         Queue<Integer> courseList = new LinkedList<Integer>();
20         for (int i = 0; i < numCourses; i++)
21             if (preNum[i] == 0) {
22                 courseList.add(i);
23             }
24 
25         int[] resList = new int[numCourses];
26         int index = 0;
27         while (!courseList.isEmpty()) {
28             int course1 = courseList.poll();
29             resList[index++] = course1;
30             List<Integer> childs = childMap.get(course1);
31             for (int course2 : childs) {
32                 preNum[course2]--;
33                 if (preNum[course2] == 0) {
34                     courseList.add(course2);
35                 }
36             }
37         }
38 
39         if (index != numCourses) return new int[0];
40         return resList;
41     }
42 }

 

相關文章