VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-cycle-in-an-undirected-unweighted-graph/

⇱ Shortest cycle in an undirected graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest cycle in an undirected graph

Last Updated : 1 Nov, 2025

Given an undirected graph represented using an adjacency list adj[][]. Find the length of the shortest cycle in the graph.
A cycle is a path that starts and ends at the same vertex without repeating any edge or vertex (except the start/end vertex). The shortest cycle is the cycle with the minimum number of edges.
If the graph does not contain any cycle, return -1.

Examples:

Input: adj[][] = [[5, 6], [4, 5, 6], [3, 6], [2, 4], [1, 3], [0, 1], [0, 1, 2]]

πŸ‘ frame_3201

Output:
Explanation: Shortest Cycle: 6 -> 1 -> 5 -> 0 -> 6

Input: adj[][] = [[5, 6], [2, 4, 5, 6], [1, 3, 6], [2, 4], [1, 3], [0, 1], [0, 1, 2]]

πŸ‘ frame_32012

Output:
Explanation: Shortest Cycle: 6 -> 1 -> 2 -> 6 

[Approach-1] Using BFS - O( V * (V+E)) Time and O(V) Space

The idea is to use Breadth-First Search (BFS) to detect the shortest cycle in a graph.
We know that BFS works level by level, so while traversing, it always finds the shortest cycle first from the starting node.
Therefore, we perform BFS from each vertex of the graph and finally take the minimum among all to get the overall shortest cycle length.

To achieve this, we perform BFS from each vertex in the graph:

  • For every vertex, start a BFS traversal.
  • Maintain a parent[] array to track the previous node (to avoid counting the same edge twice).
  • While performing BFS, if we reach a vertex that has already been visited and it is not the parent, a shortest cycle is found.
  • The current BFS level gives the length of that cycle, since BFS ensures minimal distance.
  • Repeat the above process for all vertices, keeping track of the minimum cycle length found.

Output
4

[Approach-2] Using Edge Removal - O(E*(V+E)) Time and O(V+E) Space

The idea behind this approach is by temporarily removing each edge one by one and then using BFS to check if the two vertices connected by that edge are still reachable.
If, after removing an edge (u, v), we can still reach v from u using BFS, then there exists another path between them β€” which means a cycle is formed.
The length of this cycle will be equal to the shortest path distance between u and v (found using BFS) plus one (for the removed edge itself). We repeat this process for every edge in the graph, compute the cycle length for each, and take the minimum among them as the shortest cycle length.


Output
4

Why not dfs?

DFS (Depth-First Search) goes as deep as possible before backtracking. This can easily cause it to find longer cycles first, because it doesn’t explore in increasing order of path length.
DFS can detect if a cycle exists but it cannot ensure that the first cycle found is the shortest one.

Comment