zoukankan      html  css  js  c++  java
  • Course Schedule II

    Course Schedule II

    问题:

    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, return the ordering of courses you should take to finish all courses.

    There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

    思路:

      dfs

    我的代码:

    public class Solution {
         public int[] findOrder(int numCourses, int[][] prerequisites) {
            if(prerequisites==null || prerequisites.length==0) {
                int[] a = new int[numCourses];
                for(int i=0;i<numCourses;i++) {
                    a[i]=i;
                }
                return a;
            }
            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(graph, visited, visiting, i)) return new int[0];
            }
            int[] nums = new int[numCourses];
            int i = 0;
            for(int count=rst.size()-1; count>=0; count--)
                nums[i++] = rst.get(count);
            return nums;
        }
        private List<Integer> rst = new ArrayList<Integer>();
        public boolean helper(HashSet<Integer>[] graph, boolean[] visited, boolean[] visiting, int cur)
        {
            if(visiting[cur]) return false;
            visiting[cur] = true;
            for(Integer neighbor: graph[cur])
            {
                if(visited[neighbor]) continue;
                if(!helper(graph, visited, visiting, neighbor)) return false;  
            }
            visited[cur] = true;
            visiting[cur] = false;
            rst.add(cur);
            return true;
        }
    }
    View Code

    学习之处:

    • 什么叫一个节点访问结束了,只有当这个节点的所有邻居都访问完了,才算结束了,此时visited[cur] = true;
  • 相关阅读:
    VB连接ORACAL过程
    【EXCEL】字段是否存在的查询
    ASP.NET中插入FLASH[学来得]
    做一个健康的的程序员
    SQL语法规范——Insert语句
    WEBBENCH测试网站的负载工具
    常用简易JavaScript函数(转)
    WEB服务器性能/压力测试工具HTTP_LOAD、WEBBENCH、AB、SIEGE使用教程
    Linux服务器监控SHELL脚本(自动发邮件)(转)
    空间页面CSS说明
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4511979.html
Copyright © 2011-2022 走看看