zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    python计算时间差的方法
    Apache Prefork、Worker和Event三種MPM分析
    nagios监控mysql
    linux安装nagios客户端
    简单易懂的snmpd.conf配置文件说明
    Linux基本监控项目
    python 2.0 s12 day5 常用模块介绍
    python2.0 s12 day4
    ubuntu常用系统命令
    ubuntu编译安装libimobiledevice,查看ios 日志
  • 原文地址:https://www.cnblogs.com/kpwong/p/14652631.html
Copyright © 2011-2022 走看看