Shortest Cycle in a Graph Problem
Description
LeetCode Problem 2608.
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] = [u_i, v_i] denotes an edge between vertex u_i and vertex v_i. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
Return the length of the shortest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.
Example 1:

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
Example 2:

Input: n = 4, edges = [[0,1],[0,2]]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
2 <= n <= 10001 <= edges.length <= 1000edges[i].length == 20 <= u_i, v_i < nu_i != v_i- There are no repeated edges.
Solution
Approach: Enumerate edges + BFS
Build the adjacency list g.
Every cycle contains an edge (u, v). For each edge, remove it and run a BFS from u; if v is still reachable at distance dist[v], then the shortest cycle through that edge has length dist[v] + 1. The answer is the minimum over all edges, or -1 if no edge lies on a cycle.
Complexity: time O(m * (m + n)), space O(m + n), where m is the number of edges and n the number of vertices.
from collections import defaultdict, deque
from math import inf
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