LeetCode 题解工作台
图中的最短环
现有一个含 n 个顶点的 双向 图,每个顶点按从 0 到 n - 1 标记。图中的边由二维整数数组 edges 表示,其中 edges[i] = [u i , v i ] 表示顶点 u i 和 v i 之间存在一条边。每对顶点最多通过一条边连接,并且不存在与自身相连的顶点。 返回图中 最短 环的长度…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 图·搜索
答案摘要
我们先根据数组 构建出邻接表 ,其中 表示顶点 的所有邻接点。 接下来,我们枚举双向边 $(u, v)$,如果删除该边后,从顶点 到顶点 的路径依然存在,则包含该边的最短环的长度为 $dist[v] + 1$,其中 表示从顶点 到顶点 的最短路径长度。我们取所有这样的环的最小值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
现有一个含 n 个顶点的 双向 图,每个顶点按从 0 到 n - 1 标记。图中的边由二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和 vi 之间存在一条边。每对顶点最多通过一条边连接,并且不存在与自身相连的顶点。
返回图中 最短 环的长度。如果不存在环,则返回 -1 。
环 是指以同一节点开始和结束,并且路径中的每条边仅使用一次。
示例 1:
输入:n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] 输出:3 解释:长度最小的循环是:0 -> 1 -> 2 -> 0
示例 2:
输入:n = 4, edges = [[0,1],[0,2]] 输出:-1 解释:图中不存在循环
提示:
2 <= n <= 10001 <= edges.length <= 1000edges[i].length == 20 <= ui, vi < nui != vi- 不存在重复的边
解题思路
方法一:枚举删除的边 + BFS
我们先根据数组 构建出邻接表 ,其中 表示顶点 的所有邻接点。
接下来,我们枚举双向边 ,如果删除该边后,从顶点 到顶点 的路径依然存在,则包含该边的最短环的长度为 ,其中 表示从顶点 到顶点 的最短路径长度。我们取所有这样的环的最小值即可。
时间复杂度 ,空间复杂度 。其中 和 分别为数组 的长度以及顶点数。
class Solution:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
def bfs(u: int, v: int) -> int:
dist = [inf] * n
dist[u] = 0
q = deque([u])
while q:
i = q.popleft()
for j in g[i]:
if (i, j) != (u, v) and (j, i) != (u, v) and dist[j] == inf:
dist[j] = dist[i] + 1
q.append(j)
return dist[v] + 1
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
ans = min(bfs(u, v) for u, v in edges)
return ans if ans < inf else -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that applies BFS to effectively detect cycles in graphs.
- question_mark
Assess the candidate's understanding of BFS traversal and cycle detection logic.
- question_mark
Check if the candidate optimizes the algorithm to stop early when the shortest cycle is found.
常见陷阱
外企场景- error
Forgetting to track the parent node during BFS traversal, leading to false cycle detections.
- error
Failing to account for disconnected components, which can result in missed cycles.
- error
Overcomplicating the cycle detection logic, leading to unnecessary additional operations.
进阶变体
外企场景- arrow_right_alt
Graph with directed edges.
- arrow_right_alt
Undirected graphs with weighted edges.
- arrow_right_alt
Graphs with more than one cycle.