博客
关于我
【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 360 不记住密码,JavaScript_多种方法实现360浏览器下禁止自动填写用户名密码,目前开发一个项目遇到一个很 - phpStudy...
    查看>>
    regExp的match、exec、test区别
    查看>>
    php 404 自定义,APACHE 自定义404错误页面设置方法
    查看>>
    PHP 5.3.0以上推荐使用mysqlnd驱动
    查看>>
    php aes sha1解密,PHP AES加密/解密
    查看>>
    php CI框架单个file表单多文件上传例子
    查看>>
    reflow和repaint引发的性能问题
    查看>>
    php csv 导出
    查看>>
    php curl 实例+详解
    查看>>
    php curl_init函数用法(http://blog.sina.com.cn/s/blog_640738130100tsig.html)
    查看>>
    php curl_multi批量发送http请求
    查看>>
    php echo 输出 锘?... 乱码问题
    查看>>
    ReferenceQueue的使用
    查看>>
    php flush()刷新不能输出缓冲的原因分析
    查看>>
    Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
    查看>>
    Refactoring-Imporving the Design of Exsiting Code — 代码的坏味道
    查看>>
    PHP imap 远程命令执行漏洞复现(CVE-2018-19518)
    查看>>
    php include和require
    查看>>
    ref 和out 区别
    查看>>
    php JS 导出表格特殊处理
    查看>>