#2608
Hard Algorithms Shortest cycle in a graph
Breadth-First Search Graph Theory
39.2% acceptance
Feb 25, 2026
625
20
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. 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.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn find_shortest_cycle(n: i32, edges: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let mut adj = vec![vec![]; n];
for e in &edges {
let (u, v) = (e[0] as usize, e[1] as usize);
adj[u].push(v);
adj[v].push(u);
}
let mut ans = i32::MAX;
for start in 0..n {
// BFS from start, track dist and parent
let mut dist = vec![-1i32; n];
let mut parent = vec![usize::MAX; n];
dist[start] = 0;
let mut queue = std::collections::VecDeque::new();
queue.push_back(start);
'bfs: while let Some(u) = queue.pop_front() {
for &v in &adj[u] {
if dist[v] == -1 {
dist[v] = dist[u] + 1;
parent[v] = u;
queue.push_back(v);
} else if parent[u] != v {
// Found a cycle
let cycle_len = dist[u] + dist[v] + 1;
if cycle_len < ans {
ans = cycle_len;
}
if ans == 3 {
break 'bfs;
}
}
}
}
}
if ans == i32::MAX { -1 } else { ans }
}
}