Shortest Cycle in a Graph — LeetCode 2608 Python Solution
- Problem
- #2608
- Pattern
- Breadth-First Search
- Reading time
- 4 min
- Source
- leetcode.com
The problem
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi.
Example
- Input
- n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
- Output
- 3
- Explanation
- The cycle with the smallest length is : 0 -> 1 -> 2 -> 0
Python solution
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m^2) |
| Space | O(m + n), where m and n are the length of the array edges and the number of vertices auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 2608. Shortest Cycle in a Graph is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2608. Shortest Cycle in a Graph?
- LeetCode 2608. Shortest Cycle in a Graph is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2608. Shortest Cycle in a Graph?
- The Python solution on this page runs in O(m^2).
- What is the space complexity of LeetCode 2608. Shortest Cycle in a Graph?
- The Python solution on this page uses O(m + n), where m and n are the length of the array edges and the number of vertices auxiliary space.
- What topics does LeetCode 2608. Shortest Cycle in a Graph cover?
- LeetCode 2608. Shortest Cycle in a Graph is tagged Breadth-First Search and Graph on LeetCode.