LeetCode 题解工作台

图中的最长环

给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,其中每个节点 至多 有一条出边。 图用一个大小为 n 下标从 0 开始的数组 edges 表示,节点 i 到节点 edges[i] 之间有一条有向边。如果节点 i 没有出边,那么 edges[i] == -1 。 请你返回图中的 最…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

困难 · 图·搜索

bolt

答案摘要

我们可以遍历 范围内的每个节点,如果该节点未被访问过,则从该节点出发,搜索邻边节点,直到遇到环或者遇到已经访问过的节点。如果遇到环,则更新答案。 时间复杂度 ,空间复杂度 。其中 为节点数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,其中每个节点 至多 有一条出边。

图用一个大小为 n 下标从 0 开始的数组 edges 表示,节点 i 到节点 edges[i] 之间有一条有向边。如果节点 i 没有出边,那么 edges[i] == -1 。

请你返回图中的 最长 环,如果没有任何环,请返回 -1 。

一个环指的是起点和终点是 同一个 节点的路径。

 

示例 1:

输入:edges = [3,3,4,2,3]
输出去:3
解释:图中的最长环是:2 -> 4 -> 3 -> 2 。
这个环的长度为 3 ,所以返回 3 。

示例 2:

输入:edges = [2,-1,3,1]
输出:-1
解释:图中没有任何环。

 

提示:

  • n == edges.length
  • 2 <= n <= 105
  • -1 <= edges[i] < n
  • edges[i] != i
lightbulb

解题思路

方法一:遍历出发点

我们可以遍历 [0,..,n1][0,..,n-1] 范围内的每个节点,如果该节点未被访问过,则从该节点出发,搜索邻边节点,直到遇到环或者遇到已经访问过的节点。如果遇到环,则更新答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为节点数。

相似题目:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def longestCycle(self, edges: List[int]) -> int:
        n = len(edges)
        vis = [False] * n
        ans = -1
        for i in range(n):
            if vis[i]:
                continue
            j = i
            cycle = []
            while j != -1 and not vis[j]:
                vis[j] = True
                cycle.append(j)
                j = edges[j]
            if j == -1:
                continue
            m = len(cycle)
            k = next((k for k in range(m) if cycle[k] == j), inf)
            ans = max(ans, m - k)
        return ans
speed

复杂度分析

指标
时间complexity depends on the traversal algorithm used. For DFS or BFS, it is O(n), where n is the number of nodes. Space complexity depends on the space used for marking visited nodes and storing cycle data, which is also O(n).
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate's understanding of graph traversal techniques like DFS or BFS and their ability to detect cycles.

  • question_mark

    How well the candidate can optimize space and time complexity while dealing with graph traversal.

  • question_mark

    Ability to connect the graph indegree and topological ordering patterns to detect cycles efficiently.

warning

常见陷阱

外企场景
  • error

    Confusing cycle detection with simple path finding.

  • error

    Overlooking the need for revisiting nodes that are part of a potential cycle.

  • error

    Incorrectly handling the case where no cycle exists and returning invalid results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Graphs with multiple cycles or no cycles.

  • arrow_right_alt

    Graphs where some nodes point to themselves.

  • arrow_right_alt

    Optimizing for graphs with extremely large sizes, requiring efficient traversal.

help

常见问题

外企场景

图中的最长环题解:图·搜索 | LeetCode #2360 困难