博客
关于我
【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/

    你可能感兴趣的文章
    Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
    查看>>
    Python 从数据库中存储和检索密码的最安全方法
    查看>>
    Python语言及其应用 - 知识点遍历
    查看>>
    Python 优化提速的 8 个小技巧
    查看>>
    Python 余弦相似度与皮尔逊相关系数 计算
    查看>>
    python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
    查看>>
    python 使用filetype校验文件
    查看>>
    Python 使用flush函数将缓冲区数据立即写磁盘
    查看>>
    python 使用in判断不准确,in不好使
    查看>>
    Python 使用pandas 进行查询和统计详解
    查看>>
    Redis 配置文件redis.conf详细解释
    查看>>
    python网络爬虫(2)——scrapy框架的基础使用
    查看>>
    python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
    查看>>
    Python 使用哈希函数用于加密
    查看>>
    Python 依赖管理的革新——Poetry 深度解析
    查看>>
    python 保留精度及增加去除数字的千位分隔符(金额化数字)
    查看>>
    python 倒计时 9,8,7,。。。。。。0
    查看>>
    Python 入门开发学习笔记之数据的增删改查
    查看>>
    Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
    查看>>
    Python 八大排序算法合集
    查看>>