leecode 207. 课程表

 用栈实现 比较好理解

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

 

 DFS 看起来晕车呀。

class Solution {
    List<List<Integer>> edges;
    int[] visited;
    boolean valid = true;

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        edges = new ArrayList<List<Integer>>();
        for (int i = 0; i < numCourses; ++i) {
            edges.add(new ArrayList<Integer>());
        }
        visited = new int[numCourses];
        for (int[] info : prerequisites) {
            edges.get(info[1]).add(info[0]);
        }
        for (int i = 0; i < numCourses && valid; ++i) {
            if (visited[i] == 0) {
                dfs(i);
            }
        }
        return valid;
    }

    public void dfs(int u) {
        visited[u] = 1;
        for (int v: edges.get(u)) {
            if (visited[v] == 0) {
                dfs(v);
                if (!valid) {
                    return;
                }
            } else if (visited[v] == 1) {
                valid = false;
                return;
            }
        }
        visited[u] = 2;
    }
}

 

posted @ 2021-04-13 12:30  kpwong  阅读(62)  评论(0编辑  收藏  举报