20200806: Implementation of Java Topological Sorting of Leikou 210 Curriculum Ⅱ

Likou 210: Course Schedule Ⅱ

topic

Topic link: Curriculum II
Now you have a total of n courses to choose, which are recorded as 0 to n-1.

Some prerequisite courses are required before taking certain courses. For example, if you want to study course 0, you need to complete course 1 first. We use a match to represent them: [0,1]

Given the total number of courses and their prerequisites, return to the order of study you arranged to complete all courses.

There may be multiple correct orders, you only need to return one. If it is impossible to complete all courses, return an empty array.

Insert picture description here

Ideas and algorithms

  1. Take a closer look at the same question as yesterday, just put the elements in the team into ans one by one at the end. Pay attention to judge whether there is correct output, if the repair is not completed, an empty array will be returned. See notes for the rest

Code

class Solution {
    
    
    public int[] findOrder(int numCourses, int[][] prerequisites) {
    
    
        List<Integer> list = new ArrayList<Integer>();
        int count = 0;
        
        // 注意pre数组的每一维的前后关系别弄反,后者是前者的前置依赖必修课。
        int[] beforeClassCounts = new int[numCourses]; 
        List<List<Integer>> dependencyLists = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
    
    
            dependencyLists.add(new ArrayList<>());
        }
        Queue<Integer> queue = new LinkedList<Integer>();
        // 将每个课程的入度记录下来
        // 将每个节点的 以该节点为前置依赖必修课的课程记录下来
        for (int[] pre : prerequisites) {
    
    
            beforeClassCounts[pre[0]]++;
            dependencyLists.get(pre[1]).add(pre[0]);
        }
        
        // 将入度为0的课程直接入队,获取以该课程为前置必修课的课程列表,遍历这些列表,将其入度-1。
        for (int i = 0;i < numCourses; i++) {
    
    
            if (beforeClassCounts[i] == 0) {
    
    
                queue.add(i);
            }
        }
        // 并进行判断,若这些列表中的课程此时的入度为1,即这些课程此时可以修了,将其入队。
        while (!queue.isEmpty()){
    
    
            int FinishedCourse = queue.poll();
            list.add(FinishedCourse);
            // numCourses--; 放前后都可以
            for (int cur : dependencyLists.get(FinishedCourse)) {
    
    
                if ( --beforeClassCounts[cur] == 0) {
    
    
                    queue.add(cur);
                }
            }
            numCourses--;
        }
        // 因为入队的课程已经修了,总修课程数目-1。
        //当没有入度为1的课程时判断此时的已修课程数目与必修总课程numCourse的大小关系,为0则true,否则为false。
        int[] result = new int[list.size()];
        if (numCourses != 0) {
    
    
            return new int[0];
        }
        for (int num : list) {
    
    
            result[count++] = num;
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/qq_36828395/article/details/107853429