zoukankan      html  css  js  c++  java
  • Course Schedule

    Course Schedule

    问题:

    There are a total of n courses you have to take, labeled from 0 to n - 1.

    Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

    Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

    思路:

      拓扑排序,dfs

    我的代码:

    public class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            if(numCourses<=0 || prerequisites==null || prerequisites.length==0) return true;
            HashSet<Integer>[] graph = new HashSet[numCourses];
            for(int i=0; i<numCourses; i++)
                graph[i] = new HashSet<Integer>();
            boolean[] visited = new boolean[numCourses];
            boolean[] visiting = new boolean[numCourses];
            
            for(int i=0; i<prerequisites.length; i++)
            {
                graph[prerequisites[i][1]].add(prerequisites[i][0]);
            }
            for(int i=0; i<numCourses; i++)
            {
                if(visited[i]) continue;
                if(helper(visited, visiting, graph, i) == false)    return false;
            }
            return true;
        }
        public boolean helper(boolean[] visited, boolean[] visiting, HashSet<Integer>[] graph, int j)
        {
            if(visiting[j]) return false;
            visiting[j] = true;
            
            for(Integer neighbor: graph[j])
            {
                if(visited[neighbor]) continue;
                if(helper(visited, visiting, graph, neighbor) == false) return false;
            }
            
            visiting[j] = false;
            visited[j] = true;
            return true;
        }
        
        
    }
    View Code

    学习之处:

      这道题有思路,但是一直不会写拓扑排序,主要的纠结在于如何判断是否又环,这个人的思路很赞,通过visited判断节点是否访问过,visiting用于判断是否有环。学习了。

  • 相关阅读:
    Java服务停止与开启
    跨域,php后端处理
    Mac 504 gateway timeout nginx
    Tp3.2 多数据库链接
    Redis 设置密码
    Redis 如何对外访问 lnmp安装
    tensorflow gpu安装
    ngx_http_upstream_check_module
    Nginx负载均衡+监控状态检测
    springboot+log4j2+slf4j控制台打印带sql日志
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4485006.html
Copyright © 2011-2022 走看看