Java implementation LeetCode 207 curriculum

207. curriculum

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]

A given amount of courses and their prerequisites, determine whether it is possible to complete all courses of study?

Example 1:

Input: 2 [[1,0]]
Output: true
explanation: There are two courses. Before learning Lesson 1, you need to complete the course 0. So it is possible.
Example 2:

Input: 2 [[1,0], [0,1]]
output: false
explanation: There are two courses. Before learning Lesson 1, you need to complete the course 0; 0 and before learning course, you should first complete the course 1. This is impossible.
Description:

Prerequisites input pattern is represented by an edge list, rather than adjacency matrix. Please refer to Figure representation of.
You can assume that the prerequisites are no duplicate input side.
prompt:

This problem is equivalent to find a loop exists in a directed graph. If there is circulation, topological sorting not exist, it is not possible to select all courses to learn.
Topological sorting through DFS - wonderful video tutorial on Coursera's (21 minutes), introduces the basic concepts of topological sorting.
Topological sorting can also be done through the BFS.

class Solution {
     public boolean canFinish(int numCourses, int[][] prerequisites) {
        int len = prerequisites.length;
        if(len==0) return true;
        Stack stack = new Stack();
        //存放各课程的入度
        int[] count = new int[numCourses];
        for(int i=0;i<len;i++)
            count[prerequisites[i][1]]++;
        //将入度为0的课程入栈
        for(int i=0;i<numCourses;i++)
            if(count[i]==0)
                stack.push(i);
        int m,result=0;
        //只要栈不空就循环
        while(!stack.isEmpty()){
            //每从栈顶取出一个课程,结果集加1
            m=(int) stack.pop();
            result++;
            //将与m课程连接的顶点入度减1,并判断其入度是否为0,若为0则入栈
            for(int i=0;i<len;i++)
                if(prerequisites[i][0]==m){
                    count[prerequisites[i][1]]--;
                    if(count[prerequisites[i][1]]==0)
                        stack.push(prerequisites[i][1]);
                }
        }
        //比较结果集与课程数目是否相等
        return result==numCourses;
    }
}
Released 1324 original articles · won praise 10000 + · views 1.05 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104506538