<Data Structure> topological sorting problem solving curriculum

  To do about a topological sorting exercises, problem solving curriculum with topological sorting. That LeetCode 207 questions.

  Problem Description: Now you need to choose the course a total of n, denoted by 0 to n-1. Need some Advanced Placement courses before elective certain. For example, you want to study courses 0, you need to complete Lesson 1, we use a match to represent them: [0,1] of the total courses and their prerequisites given, to determine whether it is possible to complete all courses of study.

Obviously, the topological sort can be used to accomplish such problems code is as follows:

  // numerals with the course name, starting number is 0 
    public static Boolean topSort (numCourses int, int [] [] the Prerequisites) { 
        int [] = indegree new new int [numCourses]; 
        // iterate, extracts each course penetration 
        for (int [] pre: the Prerequisites) { 
            indegree [pre [0]] ++; 
        } 
        // Create a queue used to store the degree of class 0 
        queue <Integer> queue = new LinkedList <> () ; 
        for (int I = 0; I <indegree.length; I ++) { 
            IF (indegree [I] == 0) { 
                queue.add (I); 
            } 
        } 
        // remove the head of the queue cycle courses, each taken after let the total number of courses a minus 
        the while (queue.isEmpty ()!) { 
            int k = queue.remove ();  
            // output course number
            System.out.println (k);
            numCourses--; 
            // the class that depend on the course of k minus 1, and the determination of the class is 0, if 0 is added to the queue 
            for (int [] pre: the Prerequisites) { 
                IF (pre [. 1] == K) { 
                    indegree [pre [0]] -; 
                    IF (indegree [pre [0]] == 0) { 
                        queue.add (pre [0]); 
                    } 
                } 
            } 
        } 

        // if course the total number is equal to 0, then the complete all courses 
        IF (numCourses == 0) { 
            return to true; 
        } the else { 
            return to false; 
        } 
    }

 

   
   

Guess you like

Origin www.cnblogs.com/wangxiaoqian/p/11910947.html