Shortest cycle in an undirected unweighted graph Last Updated : 18 Mar, 2022 Comments Improve Suggest changes Like Article Like Report 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. Examples: Input: Output: 4 Cycle 6 -> 1 -> 5 -> 0 -> 6 Input: Output: 3 Cycle 6 -> 1 -> 2 -> 6 Prerequisites: Dijkstra 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 the 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: C++ // C++ implementation of the approach #include <bits/stdc++.h> using namespace std; #define N 100200 vector<int> gr[N]; // Function to add edge void Add_edge(int x, int y) { gr[x].push_back(y); gr[y].push_back(x); } // Function to find the length of // the shortest cycle in the graph int shortest_cycle(int n) { // To store length of the shortest cycle int ans = INT_MAX; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum vector<int> dist(n, (int)(1e9)); // Take a imaginary parent vector<int> par(n, -1); // Distance of source to source is 0 dist[i] = 0; queue<int> q; // Push the source element q.push(i); // Continue until queue is not empty while (!q.empty()) { // Take the first element int x = q.front(); q.pop(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int)(1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } // If it is already visited else if (par[x] != child and par[child] != x) ans = min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == INT_MAX) return -1; // If graph contains cycle else return ans; } // Driver code int main() { // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call cout << shortest_cycle(n); return 0; } Java // Java implementation of the approach import java.util.*; class GFG { static final int N = 100200; @SuppressWarnings("unchecked") static Vector<Integer>[] gr = new Vector[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = Integer.MAX_VALUE; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; Arrays.fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; Arrays.fill(par, -1); // Distance of source to source is 0 dist[i] = 0; Queue<Integer> q = new LinkedList<>(); // Push the source element q.add(i); // Continue until queue is not empty while (!q.isEmpty()) { // Take the first element int x = q.poll(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.add(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == Integer.MAX_VALUE) return -1; // If graph contains cycle else return ans; } // Driver Code public static void main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new Vector<>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call System.out.println(shortest_cycle(n)); } } // This code is contributed by // sanjeev2552 Python3 # Python3 implementation of the approach from sys import maxsize as INT_MAX from collections import deque N = 100200 gr = [0] * N for i in range(N): gr[i] = [] # Function to add edge def add_edge(x: int, y: int) -> None: global gr gr[x].append(y) gr[y].append(x) # Function to find the length of # the shortest cycle in the graph def shortest_cycle(n: int) -> int: # To store length of the shortest cycle ans = INT_MAX # For all vertices for i in range(n): # Make distance maximum dist = [int(1e9)] * n # Take a imaginary parent par = [-1] * n # Distance of source to source is 0 dist[i] = 0 q = deque() # Push the source element q.append(i) # Continue until queue is not empty while q: # Take the first element x = q[0] q.popleft() # Traverse for all it's childs for child in gr[x]: # If it is not visited yet if dist[child] == int(1e9): # Increase distance by 1 dist[child] = 1 + dist[x] # Change parent par[child] = x # Push into the queue q.append(child) # If it is already visited elif par[x] != child and par[child] != x: ans = min(ans, dist[x] + dist[child] + 1) # If graph contains no cycle if ans == INT_MAX: return -1 # If graph contains cycle else: return ans # Driver Code if __name__ == "__main__": # Number of vertices n = 7 # Add edges add_edge(0, 6) add_edge(0, 5) add_edge(5, 1) add_edge(1, 6) add_edge(2, 6) add_edge(2, 3) add_edge(3, 4) add_edge(4, 1) # Function call print(shortest_cycle(n)) # This code is contributed by # sanjeev2552 C# // C# implementation of the approach using System; using System.Collections.Generic; class GFG { static readonly int N = 100200; static List<int>[] gr = new List<int>[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = int.MaxValue; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; fill(par, -1); // Distance of source to source is 0 dist[i] = 0; List<int> q = new List<int>(); // Push the source element q.Add(i); // Continue until queue is not empty while (q.Count!=0) { // Take the first element int x = q[0]; q.RemoveAt(0); // Traverse for all it's childs foreach (int child in gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.Add(child); } else if (par[x] != child && par[child] != x) ans = Math.Min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == int.MaxValue) return -1; // If graph contains cycle else return ans; } static int[] fill(int []arr, int val) { for(int i = 0;i<arr.GetLength(0);i++) arr[i] = val; return arr; } // Driver Code public static void Main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new List<int>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call Console.WriteLine(shortest_cycle(n)); } } // This code is contributed by 29AjayKumar JavaScript <script> // JavaScript implementation of the approach var N = 100200; var gr = Array.from(Array(N),()=>Array()); // Function to add edge function Add_edge(x, y) { gr[x].push(y); gr[y].push(x); } // Function to find the length of // the shortest cycle in the graph function shortest_cycle(n) { // To store length of the shortest cycle var ans = 1000000000; // For all vertices for(var i = 0; i < n; i++) { // Make distance maximum var dist = Array(n).fill(1000000000); // Take a imaginary parent var par = Array(n).fill(-1); // Distance of source to source is 0 dist[i] = 0; var q = []; // Push the source element q.push(i); // Continue until queue is not empty while (q.length!=0) { // Take the first element var x = q[0]; q.shift(); // Traverse for all it's childs for(var child of gr[x]) { // If it is not visited yet if (dist[child] == 1000000000) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == 1000000000) return -1; // If graph contains cycle else return ans; } function fill(arr, val) { for(var i = 0;i<arr.length;i++) arr[i] = val; return arr; } // Driver Code // Number of vertices var n = 7; // push edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call document.write(shortest_cycle(n)); </script> Output: 4 Time Complexity: O( |V| * (|V|+|E|)) for a graph G=(V, E) Memory Complexity: O(V^2) for a graph G=(V, E) Comment More infoAdvertise with us Next Article Shortest cycle in an undirected unweighted graph P pawan_asipu Follow Improve Article Tags : Graph Advanced Data Structure DSA Dijkstra graph-cycle +1 More Practice Tags : Advanced Data StructureGraph Similar Reads What is Dijkstraâs Algorithm? | Introduction to Dijkstra's Shortest Path Algorithm In this article, we will be discussing one of the most commonly known shortest-path algorithms i.e. Dijkstra's Shortest Path Algorithm which was developed by Dutch computer scientist Edsger W. Dijkstra in 1956. Moreover, we will do a complexity analysis for this algorithm and also see how it differs 10 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Dijkstraâs Algorithm for Adjacency List Representation | Greedy Algo-8 The Dijkstra's Algorithm, we can either use the matrix representation or the adjacency list representation to represent the graph, while the time complexity of Dijkstra's Algorithm using matrix representation is O(V^2). The time complexity of Dijkstra's Algorithm using adjacency list representation 15+ min read Printing Paths in Dijkstra's Shortest Path Algorithm Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.We have discussed Dijkstra's Shortest Path algorithm in the below posts. Dijkstraâs shortest path for adjacency matrix representationDijkstraâs shortest path for adjacency list 15 min read Why does Dijkstra's Algorithm fail on negative weights? Dijkstra's Algorithm: It is a graph searching algorithm that uses a Greedy Approach to find the shortest path from the source node to all other remaining nodes. It solves the single-source shortest path problem for a weighted graph. This algorithm keeps track of the weights of the edges for finding 4 min read Applications of Dijkstra's shortest path algorithm Dijkstraâs algorithm is one of the most popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 4 min read Dijkstra's Algorithm in different languageC / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7Problem Statement: Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. What is Dijkstra's Algorithm? Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate an SPT (shorte 5 min read Java Program for Dijkstra's shortest path algorithm | Greedy Algo-7Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate a SPT (shortest path tree) with given source as root. We maintain two s 5 min read Dijkstra's shortest path algorithm in PythonGiven a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph. Dijkstraâs algorithm is a popular algorithm for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest dis 4 min read C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate a SPT (shortest path tree) with given source as root. We maintain two s 5 min read Different ways to implement Dijkstra's algorithmDijkstraâs shortest path algorithm using setGiven a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Example:Input: src = 0, V = 5, edges[][] = [[0, 1, 4], [0, 2, 8], 8 min read Dijkstra's Shortest Path Algorithm using priority_queue of STLGiven a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph.Input : Source = 0Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14We have discussed Dijkstraâs shortest Path implementations.Dijkstraâs Algorithm for Adjacency 15+ min read Dijkstra's shortest path algorithm in Java using PriorityQueueDijkstraâs algorithm is very similar to Primâs algorithm for minimum spanning tree. Like Primâs MST, we generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices included in the shortest-path tree, other set includes vertices not yet included 5 min read Variations of Dijkstra's algorithmMinimum Cost using Dijkstra by Modifying Cost of an EdgeGiven an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that 15 min read Minimum cost path from source node to destination node via an intermediate nodeGiven an undirected weighted graph. The task is to find the minimum cost of the path from source node to the destination node via an intermediate node. Note: If an edge is traveled twice, only once weight is calculated as cost. Examples: Input: source = 0, destination = 2, intermediate = 3; Output: 12 min read Find Maximum Shortest Distance in Each Component of a GraphGiven an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes. Examples: Input: Output: 8 0 11 Explanation: There are thre 15+ min read Comparison of Dijkstraâs and FloydâWarshall algorithmsDijkstra AlgorithmDijkstraâs Algorithm is a Single-Source Shortest Path SSSP algorithm, i.e., given a source vertex it finds the shortest path from the source to all other vertices. The idea is to generate a SPT (shortest path tree) with a given source as a root and with two sets, one set contains v 4 min read Minimum Weight Cycle in a Graph Given an undirected, weighted graph with V vertices numbered from 0 to V-1, and E edges represented as a 2D array edges[][], where each element edges[i] = [u, v, w] denotes an edge between nodes u and v with weight w, and all edge weights are positive integers, your task is to find the minimum weigh 15+ min read Like