博客
关于我
【Lintcode】1366. Directed Graph Loop
阅读量:200 次
发布时间:2019-02-28

本文共 2022 字,大约阅读时间需要 6 分钟。

给定一个有向图,判断其是否存在环。图有n个顶点,标号从1到n。每个顶点可以有出边,但没有入边的限制。

方法思路

为了判断有向图是否存在环,可以使用深度优先搜索(DFS)进行遍历。具体步骤如下:

  • 构建邻接表:使用哈希表存储每个顶点的出边。
  • 初始化访问标记数组:标记每个顶点的访问状态,状态包括:未访问(-1)、当前访问(0)和已访问(1)。
  • 遍历每个顶点:对于每个未访问的顶点,进行DFS遍历。
  • DFS遍历
    • 标记当前顶点为“当前访问”状态。
    • 遍历当前顶点的所有出边。
    • 如果发现邻接顶点处于“当前访问”状态,说明存在环,返回true。
    • 如果邻接顶点未被访问过,进行递归DFS。
    • 在递归返回后,标记当前顶点为“已访问”状态,返回false。
  • 代码实现

    import java.util.*;public class Solution {    public boolean isCyclicGraph(int[] start, int[] end) {        if (start == null || start.length == 0) {            return false;        }                int n = 0;        for (int s : start) {            n = Math.max(n, s);        }        for (int e : end) {            n = Math.max(n, e);        }                Map
    > graph = buildGraph(start, end); int[] visited = new int[n + 1]; Arrays.fill(visited, -1); for (int i = 1; i <= n; i++) { if (visited[i] == -1 && dfs(graph, i, visited)) { return true; } } return false; } private boolean dfs(Map
    > graph, int cur, int[] visited) { visited[cur] = 0; List
    neighbors = graph.get(cur); if (neighbors != null) { for (int next : neighbors) { if (visited[next] == 0) { return true; } if (visited[next] == -1 && dfs(graph, next, visited)) { return true; } } } visited[cur] = 1; return false; } private Map
    > buildGraph(int[] start, int[] end) { Map
    > graph = new HashMap<>(); for (int i = 0; i < start.length; i++) { int s = start[i]; int e = end[i]; if (graph.containsKey(s)) { graph.get(s).add(e); } else { graph.put(s, new ArrayList<>()); graph.get(s).add(e); } } return graph; }}

    时间复杂度

    • V:顶点数
    • E:边数
    • 时间复杂度为O(V + E),适用于大多数情况。

    转载地址:http://bhds.baihongyu.com/

    你可能感兴趣的文章
    php-兔子问题,斐波那契数列
    查看>>
    PHP-希尔排序
    查看>>
    PHP-快速排序的2种实现方法
    查看>>
    php-数据结构-二叉树的构建、前序遍历,中序遍历,后序遍历,查找,打印
    查看>>
    php-有序数组合并后仍有序
    查看>>
    redis使用
    查看>>
    Redis以及Redis的php扩展安装
    查看>>
    PHP-算法-最少比较次数获取最大值最小值
    查看>>
    php-约瑟夫问题
    查看>>
    Redis从库不能同步报Can’t save in background: fork: Cannot allocate memory错误
    查看>>
    Redis从入门到精通|干货篇
    查看>>
    php.ini maxfileuploads,细说PHP高洛峰文件上传类源文件
    查看>>
    php.ini中常见的配置信息选项
    查看>>
    php.ini配置中有10处设置不当,会使网站存在安全问题
    查看>>
    php/jsp/asp的区别
    查看>>
    php20个主流框架
    查看>>
    php301到https,虚拟主机设置自动301跳转到HTTPS
    查看>>
    php5 apache 配置
    查看>>
    php5 升级 php7 版本遇到的问题处理方法总结
    查看>>
    PHP5.3.3安装Mcrypt扩展
    查看>>