[LeetCode 210] Course Schedule II (Medium)

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.

Example 1:

Input: 2, [[1,0]] 
Output: `[0,1]`
Explanation: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] .`</pre>

Example 2:

**Input:** 4, [[1,0],[2,0],[3,1],[3,2]]
**Output:** `[0,1,2,3] or [0,2,1,3]`
**Explanation:** 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] .`</pre>

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

SOLUTION1: DFS VS SOLUTION2: BFS + INDEGREE

区别只在于需要记录路径

class Solution {
    /*************************** Solution 1 DFS ************************************
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        //1. Generate nodeVsNeighbors map
        Map<Integer, List<Integer>> nodeVsNeighbors = new HashMap<> ();
        for (int i = 0; i < prerequisites.length; i++) {
            int course = prerequisites[i][0];
            int preCourse = prerequisites[i][1];
            
            List<Integer> courses = nodeVsNeighbors.getOrDefault (preCourse, new ArrayList<Integer> ());
            courses.add (course);
            nodeVsNeighbors.put (preCourse, courses);
        }
        
        
        //2. 
        boolean[] visited = new boolean[numCourses];
        boolean[] recStack = new boolean [numCourses];
        Stack<Integer> tracker = new Stack<> ();
        
        for (int i = 0; i < numCourses; i++) {
            if (!visited[i]) {
                if (findOrderHelper (nodeVsNeighbors, visited, recStack, tracker, i))
                    return new int[0];
            }
        }
        
        int[] result = new int[tracker.size ()];
        int index = 0;
        
        while (!tracker.isEmpty ()) {
            result[index++] = tracker.pop ();
        }
        
        return result;
    }
    
    public boolean findOrderHelper (Map<Integer, List<Integer>> nodeVsNeighbors, boolean[] visited, boolean[] recStack, Stack<Integer> tracker, int currentIndex) {
        if (recStack[currentIndex])
            return true;
        
        if (visited[currentIndex])
            return false;
        
        visited[currentIndex] = true;
        recStack[currentIndex] = true;
        
        for (int nextCourse : nodeVsNeighbors.getOrDefault (currentIndex, new ArrayList<Integer> ())) {
            if (findOrderHelper (nodeVsNeighbors, visited, recStack, tracker, nextCourse))
                return true;
        }
        
        recStack[currentIndex] = false;
        tracker.push (currentIndex);
        return false;
    }
    ************************************ Solution 1 END ************************/
    public int[] findOrder(int numCourses, int[][] prerequisites) {
//         if (prerequisites == null || prerequisites.length == 0 || prerequisites[0].length == 0) {
//             return true;
//         }
        
//         if (numCourses == 0) {
//             return true;
//         }
        
        
        //1, get preCourseVsCourses Map  and ZeroDegree map
        Map<Integer, List<Integer>> preCourseVsCourses = new HashMap<> ();
        Map<Integer, Integer> zeroDegree = new HashMap <> ();
        
        for (int i = 0; i < prerequisites.length; i++) {
            int preCourse = prerequisites[i][1];
            int course = prerequisites[i][0];
            
            List<Integer> courses = preCourseVsCourses.getOrDefault (preCourse, new ArrayList<Integer> ());
            courses.add (course);
            preCourseVsCourses.put (preCourse, courses);
            
            int degree = zeroDegree.getOrDefault (course, 0);
            zeroDegree.put (course, degree + 1);
        }
        
        //2. Put all node with zero degree into a queue
        Queue<Integer> queue1 = new LinkedList<> ();
        for (int i = 0; i < numCourses; i++) {
            if (!zeroDegree.containsKey (i) || zeroDegree.get (i) == 0) {
                queue1.offer (i);
            }
        }
        
        //3. try to find if there is a cycle or can visit all
        Queue<Integer> queue2 = new LinkedList<> ();
        int countOfZeroDegreeCourse = 0;
        int[] result = new int[numCourses];
        int index = 0;
        
        while (!queue1.isEmpty ()) {
            int currentCourse = queue1.poll ();
            countOfZeroDegreeCourse ++;
            result [index ++] = currentCourse;
                
            for (int nextCourse : preCourseVsCourses.getOrDefault (currentCourse, new ArrayList<Integer> ())) {
                if (zeroDegree.containsKey (nextCourse)) {
                    int degree = zeroDegree.get (nextCourse);
                    zeroDegree.put (nextCourse, degree - 1);
                    
                    if (degree - 1 == 0) {
                        queue2.offer (nextCourse);
                    }
                }
            }
            
            if (queue1.isEmpty ()) {
                queue1 = queue2;
                queue2 = new LinkedList<Integer> ();
            }
        }
        
        return countOfZeroDegreeCourse == numCourses ? result : new int[0];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容