美文网首页
[LeetCode 210] Course Schedule I

[LeetCode 210] Course Schedule I

作者: 灰睛眼蓝 | 来源:发表于2019-06-10 06:22 被阅读0次

    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];
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 210] Course Schedule I

          本文链接:https://www.haomeiwen.com/subject/tbtaxctx.html