zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge29 之 拓扑排序

    本题是一个很经典的图论问题,可以简化为判断有向图是否有环。

    class Solution {
        private Map<Integer, List<Integer>> graph= new HashMap<>();
        private int[] visited;
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            for(int[] edge: prerequisites){
                graph.putIfAbsent(edge[1], new ArrayList<>());
                graph.get(edge[1]).add(edge[0]);
            }
            // states: 0 = unknown, 1 == visiting, 2 = visited
            visited = new int[numCourses];
            for(int node = 0; node < numCourses; node++){
                if(visited[node] == 0 && isCycle(node))
                    return false;
            }
            return true;
        }
        public boolean isCycle(int cur){
            if(visited[cur] == 1) return true;
            if(visited[cur] == 2) return false;
            if(!graph.containsKey(cur)) return false;
            //bug 先返回 再赋值
            visited[cur] = 1;
            for(int next: graph.get(cur)){
                if(isCycle(next)) return true;
            }
            visited[cur] = 2;
            return false;
        }
    }
  • 相关阅读:
    WPF 绘图 和动画
    BZOJ 4028 分块
    操作系统与计算机网络
    go排序-基数排序
    go排序-睡眠排序
    go排序-堆排序
    go排序-构建大顶堆
    go排序 插入排序
    go排序-选择排序
    go排序-冒泡排序
  • 原文地址:https://www.cnblogs.com/yawenw/p/13034191.html
Copyright © 2011-2022 走看看