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用于判断是否有环。学习了。

  • 相关阅读:
    手把手教你安装系统-只需一个U盘
    Linux系统优化05-Centos修改主机名
    Linux系统优化06-Centos远程登录与连接(SSH配置)
    数据库ACID
    Java中的String,StringBuilder,StringBuffer三者的区别
    zookeeper的选举机制
    mysql的数据类型
    常用类(四)
    常用类(三)
    常用类(二)
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4485006.html
Copyright © 2011-2022 走看看