Detect cycle in an undirected graph
Last Updated :
07 Apr, 2025
Given an undirected graph, the task is to check if there is a cycle in the given graph.
Examples:
Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]]
Undirected Graph with 4 vertices and 4 edgesOutput: true
Explanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0
Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]]
Undirected graph with 4 vertices and 3 edgesOutput: false
Explanation: There is no cycle in the given graph.
Using Breadth First Search - O(V+E) Time and O(V) Space
BFS is useful for cycle detection in an undirected graph because it explores level by level, ensuring that each node is visited in the shortest possible way. It efficiently detects cycles using a visited array and a queue while avoiding unnecessary recursive calls, making it more memory-efficient than DFS for large graphs.
During BFS traversal, we maintain a visited array and a queue. We process nodes by popping them one by one from the queue, marking them as visited, and pushing their unvisited adjacent nodes into the queue. A cycle is detected if we encounter a node that has already been visited before being dequeued, meaning it has been reached through a different path. This approach ensures that we efficiently detect cycles while maintaining optimal performance.
Please refer Detect cycle in an undirected graph using BFS for complete implementation.
Using Depth First Search - O(V+E) Time and O(V) Space
Depth First Traversal can be used to detect a cycle in an undirected Graph. If we encounter a visited vertex again, then we say, there is a cycle. But there is a catch in this algorithm, we need to make sure that we do not consider every edge as a cycle because in an undirected graph, an edge from 1 to 2 also means an edge from 2 to 1. To handle this, we keep track of the parent node (the node from which we came to the current node) in the DFS traversal and ignore the parent node from the visited condition.
Follow the below steps to implement the above approach:
- Iterate over all the nodes of the graph and Keep a visited array visited[] to track the visited nodes.
- If the current node is not visited, run a Depth First Traversal on the given subgraph connected to the current node and pass the parent of the current node as -1. Recursively, perform the following steps:
- Set visited[root] as 1.
- Iterate over all adjacent nodes of the current node in the adjacency list
- If it is not visited then run DFS on that node and return true if it returns true.
- Else if the adjacent node is visited and not the parent of the current node then return true.
- Return false.
Illustration:
Below is the graph showing how to detect cycle in a graph using DFS:
Below is the implementation of the above approach:
C++
// A C++ Program to detect cycle in an undirected graph
#include <bits/stdc++.h>
using namespace std;
bool isCycleUtil(int v, vector<vector<int>> &adj, vector<bool> &visited, int parent)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
for (int i : adj[v])
{
// If an adjacent vertex is not visited, then recur for that adjacent
if (!visited[i])
{
if (isCycleUtil(i, adj, visited, v))
return true;
}
// If an adjacent vertex is visited and is not parent of current vertex,
// then there exists a cycle in the graph.
else if (i != parent)
return true;
}
return false;
}
vector<vector<int>> constructadj(int V, vector<vector<int>> &edges){
vector<vector<int>> adj(V);
for (auto it : edges)
{
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
return adj;
}
// Returns true if the graph contains a cycle, else false.
bool isCycle(int V, vector<vector<int>> &edges)
{
vector<vector<int>> adj = constructadj(V,edges);
// Mark all the vertices as not visited
vector<bool> visited(V, false);
for (int u = 0; u < V; u++)
{
if (!visited[u])
{
if (isCycleUtil(u, adj, visited, -1))
return true;
}
}
return false;
}
int main()
{
int V = 5;
vector<vector<int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {3, 4}};
if (isCycle(V, edges))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}
Java
import java.util.*;
class GfG {
// Helper function to check cycle using DFS
static boolean isCycleUtil(int v, List<Integer>[] adj,
boolean[] visited,
int parent)
{
visited[v] = true;
// If an adjacent vertex is not visited,
// then recur for that adjacent
for (int i : adj[v]) {
if (!visited[i]) {
if (isCycleUtil(i, adj, visited, v))
return true;
}
// If an adjacent vertex is visited and
// is not parent of current vertex,
// then there exists a cycle in the graph.
else if (i != parent) {
return true;
}
}
return false;
}
static List<Integer>[] constructadj(int V, int [][] edges){
List<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
return adj;
}
// Function to check if graph contains a cycle
static boolean isCycle(int V, int[][] edges)
{
List<Integer> [] adj = constructadj(V,edges);
for (int[] edge : edges) {
adj[edge[0]].add(edge[1]);
adj[edge[1]].add(edge[0]);
}
boolean[] visited = new boolean[V];
// Call the recursive helper function
// to detect cycle in different DFS trees
for (int u = 0; u < V; u++) {
if (!visited[u]) {
if (isCycleUtil(u, adj, visited, -1))
return true;
}
}
return false;
}
public static void main(String[] args)
{
int V = 5;
int[][] edges = {
{0, 1}, {0, 2}, {0, 3}, {1, 2}, {3, 4}
};
if (isCycle(V, edges)) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
Python
# Helper function to check cycle using DFS
def isCycleUtil(v, adj, visited, parent):
visited[v] = True
for i in adj[v]:
if not visited[i]:
if isCycleUtil(i, adj, visited, v):
return True
elif i != parent:
return True
return False
def constructadj(V, edges):
adj = [[] for _ in range(V)] # Initialize adjacency list
for edge in edges:
u, v = edge
adj[u].append(v)
adj[v].append(u)
return adj
# Function to check if graph contains a cycle
def isCycle(V, edges):
adj = constructadj(V,edges)
visited = [False] * V
for u in range(V):
if not visited[u]:
if isCycleUtil(u, adj, visited, -1):
return True
return False
# Driver Code
if __name__ == "__main__":
V = 5
edges = [(0, 1), (0, 2), (0, 3), (1, 2), (3, 4)]
if isCycle(V, edges):
print("true")
else:
print("false")
C#
using System;
using System.Collections.Generic;
class CycleDetection {
// Helper function to check cycle using DFS
static bool IsCycleUtil(int v, List<int>[] adj,
bool[] visited, int parent)
{
visited[v] = true;
foreach(int i in adj[v])
{
if (!visited[i]) {
if (IsCycleUtil(i, adj, visited, v))
return true;
}
else if (i != parent) {
return true;
}
}
return false;
}
static List<int>[] constructadj(int V, int [,] edges){
List<int>[] adj = new List<int>[ V ];
for (int i = 0; i < V; i++) {
adj[i] = new List<int>();
}
return adj;
}
// Function to check if graph contains a cycle
static bool IsCycle(int V, int[, ] edges)
{
List<int>[] adj = constructadj(V,edges);
for (int i = 0; i < edges.GetLength(0); i++) {
int u = edges[i, 0], v = edges[i, 1];
adj[u].Add(v);
adj[v].Add(u);
}
bool[] visited = new bool[V];
for (int u = 0; u < V; u++) {
if (!visited[u]) {
if (IsCycleUtil(u, adj, visited, -1))
return true;
}
}
return false;
}
public static void Main()
{
int V = 5;
int[, ] edges = {
{ 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 2 }, { 3, 4 }
};
if (IsCycle(V, edges)) {
Console.WriteLine("true");
}
else {
Console.WriteLine("false");
}
}
}
JavaScript
// Helper function to check cycle using DFS
function isCycleUtil(v, adj, visited, parent)
{
visited[v] = true;
for (let i of adj[v]) {
if (!visited[i]) {
if (isCycleUtil(i, adj, visited, v)) {
return true;
}
}
else if (i !== parent) {
return true;
}
}
return false;
}
function constructadj(V, edges){
let adj = Array.from({length : V}, () => []);
// Build the adjacency list
for (let edge of edges) {
let [u, v] = edge;
adj[u].push(v);
adj[v].push(u);
}
return adj;
}
// Function to check if graph contains a cycle
function isCycle(V, edges)
{
let adj = constructadj(V,edges);
let visited = new Array(V).fill(false);
// Check each node
for (let u = 0; u < V; u++) {
if (!visited[u]) {
if (isCycleUtil(u, adj, visited, -1)) {
return true;
}
}
}
return false;
}
// Driver Code
const V = 5;
const edges =
[[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]];
if (isCycle(V, edges)) {
console.log("true");
}
else {
console.log("false");
}
Time Complexity: O(V+E) because DFS visits each vertex once (O(V)) and traverses all edges once (O(E))
Auxiliary space: O(V) for the visited array and O(V) for the recursive call stack.
We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
Related Articles:
Similar Reads
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
DFS in different language
Iterative Depth First Traversal of Graph
Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
10 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
2 min read
Depth First Search or DFS for disconnected Graph
Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Disconnected Graph Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given sour
7 min read
Printing pre and post visited times in DFS of a graph
Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored
8 min read
Tree, Back, Edge and Cross Edges in DFS of Graph
Given a directed graph, the task is to identify tree, forward, back and cross edges present in the graph.Note: There can be multiple answers.Example:Input: GraphOutput:Tree Edges: 1->2, 2->4, 4->6, 1->3, 3->5, 5->7, 5->8 Forward Edges: 1->8 Back Edges: 6->2 Cross Edges: 5-
9 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
8 min read
Variations of DFS implementations