Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1.
Cycle 6 -> 1 -> 5 -> 0 -> 6
Cycle 6 -> 1 -> 2 -> 6
Approach: For every vertex, we check if it is possible to get the shortest cycle involving this vertex. For every vertex first, push current vertex into the queue and then it’s neighbours and if vertex which is already visited comes again then the cycle is present.
Apply the above process for every vertex and get the length of the shortest cycle.
Below is the implementation of the above approach:
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Shortest path in an unweighted graph
- Number of shortest paths in an unweighted and directed graph
- Multi Source Shortest Path in Unweighted Graph
- Detect cycle in an undirected graph using BFS
- Detect cycle in an undirected graph
- Check if there is a cycle with odd weight sum in an undirected graph
- Number of single cycle components in an undirected graph
- Find minimum weight cycle in an undirected graph
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Detect cycle in the graph using degrees of nodes of graph
- Clone an Undirected Graph
- Number of Triangles in an Undirected Graph
- Sum of degrees of all nodes of a undirected graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sanjeev2552