Detect cycle in an undirected graph
Last Updated :
09 Aug, 2024
Given an undirected graph, The task is to check if there is a cycle in the given graph.
Examples:
Input: V = 4, E = 4

Undirected Graph with 4 vertices and 4 edges
Output: Yes
Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0
Input: V = 4, E = 3

Undirected graph with 4 vertices and 3 edges
Output: No
Explanation: There is no cycle in the given graph.
When we do BFS traversal, we maintain a visited array and a queue. We pop items one by one from the queue, mark the popped items as visited and consider the non-visited adjacent and push them into the queue. If we mark the vertices visited, when we take out them from the queue, we can detect cycle by simply checking if a visited node is taken out again from the queue. Please refer the above linked post for complete implementation.
Find cycle in Undirected Graph using DFS:
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.
- Run a Depth First Traversal on the given subgraph connected to the current node and pass the parent of the current node. In each recursive
- 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 <iostream>
#include <vector>
using namespace std;
// A recursive function that
// uses visited[] and parent to detect
// cycle in subgraph reachable
// from vertex v.
bool isCyclicUtil(int v, vector<vector<int>>& adj,
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 (isCyclicUtil(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;
}
// Returns true if the graph contains
// a cycle, else false.
bool isCyclic(int V, vector<vector<int>>& adj) {
// Mark all the vertices as not visited
bool* visited = new bool[V]{false};
// Call the recursive helper function
// to detect cycle in different DFS trees
for (int u = 0; u < V; u++) {
// Don't recur for u if it is already visited
if (!visited[u])
if (isCyclicUtil(u, adj, visited, -1))
return true;
}
return false;
}
// Driver program to test above functions
int main() {
int V = 3;
vector<vector<int>> adj(V);
adj[1].push_back(0);
adj[0].push_back(1);
adj[0].push_back(2);
adj[2].push_back(0);
adj[1].push_back(2);
adj[2].push_back(1);
isCyclic(V, adj) ? cout << "Contains cycle\n"
: cout << "No Cycle\n";
V = 3;
vector<vector<int>> adj2(V);
adj2[0].push_back(1);
adj2[1].push_back(0);
adj2[1].push_back(2);
adj2[2].push_back(1);
isCyclic(V, adj2) ? cout << "Contains Cycle\n"
: cout << "No Cycle\n";
return 0;
}
Java
// A Java Program to detect
// cycle in an undirected graph
import java.util.*;
public class GfG {
// A recursive function that
// uses visited[] and parent to detect
// cycle in subgraph reachable
// from vertex v.
static boolean isCyclicUtil(int v, List<List<Integer>> adj,
boolean[] 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.get(v)) {
// If an adjacent vertex is not visited,
// then recur for that adjacent
if (!visited[i]) {
if (isCyclicUtil(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;
}
// Returns true if the graph contains
// a cycle, else false.
static boolean isCyclic(int V, List<List<Integer>> adj) {
// Mark all the vertices as not visited
boolean[] visited = new boolean[V];
// Call the recursive helper function
// to detect cycle in different DFS trees
for (int u = 0; u < V; u++) {
// Don't recur for u if it is already visited
if (!visited[u]) {
if (isCyclicUtil(u, adj, visited, -1))
return true;
}
}
return false;
}
// Driver program to test above functions
public static void main(String[] args) {
int V = 3;
List<List<Integer>> adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
adj.get(1).add(0);
adj.get(0).add(1);
adj.get(0).add(2);
adj.get(2).add(0);
adj.get(1).add(2);
adj.get(2).add(1);
System.out.println(isCyclic(V, adj) ?
"Contains cycle" : "No Cycle");
V = 3;
List<List<Integer>> adj2 = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj2.add(new ArrayList<>());
}
adj2.get(0).add(1);
adj2.get(1).add(0);
adj2.get(1).add(2);
adj2.get(2).add(1);
System.out.println(isCyclic(V, adj2) ?
"Contains Cycle" : "No Cycle");
}
}
Python
# A Python Program to detect
# cycle in an undirected graph
def is_cyclic_util(v, adj, visited, parent):
# Mark the current node as visited
visited[v] = True
# Recur for all the vertices
# adjacent to this vertex
for i in adj[v]:
# If an adjacent vertex is not visited,
# then recur for that adjacent
if not visited[i]:
if is_cyclic_util(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.
elif i != parent:
return True
return False
def is_cyclic(V, adj):
# Mark all the vertices as not visited
visited = [False] * V
# Call the recursive helper function
# to detect cycle in different DFS trees
for u in range(V):
# Don't recur for u if it is already visited
if not visited[u]:
if is_cyclic_util(u, adj, visited, -1):
return True
return False
# Driver program to test above functions
if __name__ == "__main__":
V = 3
adj = [[] for _ in range(V)]
adj[1].append(0)
adj[0].append(1)
adj[0].append(2)
adj[2].append(0)
adj[1].append(2)
adj[2].append(1)
print("Contains cycle" if is_cyclic(V, adj) else "No Cycle")
V = 3
adj2 = [[] for _ in range(V)]
adj2[0].append(1)
adj2[1].append(0)
adj2[1].append(2)
adj2[2].append(1)
print("Contains Cycle" if is_cyclic(V, adj2) else "No Cycle")
C#
using System;
using System.Collections.Generic;
public class CycleDetection
{
// A recursive function that uses visited[] and parent to detect
// cycle in subgraph reachable from vertex v.
static bool IsCyclicUtil(int v, List<List<int>> adj,
bool[] visited, int parent)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
foreach (int i in adj[v])
{
// If an adjacent vertex is not visited,
// then recur for that adjacent
if (!visited[i])
{
if (IsCyclicUtil(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;
}
// Returns true if the graph contains a cycle, else false.
static bool IsCyclic(int V, List<List<int>> adj)
{
// Mark all the vertices as not visited
bool[] visited = new bool[V];
// Call the recursive helper function to detect
// cycle in different DFS trees
for (int u = 0; u < V; u++)
{
// Don't recur for u if it is already visited
if (!visited[u])
{
if (IsCyclicUtil(u, adj, visited, -1))
return true;
}
}
return false;
}
// Example usage:
static void Main()
{
int V = 3;
List<List<int>> adj = new List<List<int>>(V);
for (int i = 0; i < V; i++)
adj.Add(new List<int>());
adj[1].Add(0);
adj[0].Add(1);
adj[0].Add(2);
adj[2].Add(0);
adj[1].Add(2);
adj[2].Add(1);
Console.WriteLine(IsCyclic(V, adj) ?
"Contains cycle" : "No Cycle");
V = 3;
List<List<int>> adj2 = new List<List<int>>(V);
for (int i = 0; i < V; i++)
adj2.Add(new List<int>());
adj2[0].Add(1);
adj2[1].Add(0);
adj2[1].Add(2);
adj2[2].Add(1);
Console.WriteLine(IsCyclic(V, adj2) ?
"Contains Cycle" : "No Cycle");
}
}
JavaScript
// A JavaScript Program to detect
// cycle in an undirected graph
function isCyclicUtil(v, adj, visited, parent) {
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices
// adjacent to this vertex
for (let i of adj[v]) {
// If an adjacent vertex is not visited,
// then recur for that adjacent
if (!visited[i]) {
if (isCyclicUtil(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;
}
function isCyclic(V, adj) {
// Mark all the vertices as not visited
const visited = new Array(V).fill(false);
// Call the recursive helper function
// to detect cycle in different DFS trees
for (let u = 0; u < V; u++) {
// Don't recur for u if it is already visited
if (!visited[u]) {
if (isCyclicUtil(u, adj, visited, -1)) {
return true;
}
}
}
return false;
}
// Example usage:
let V = 3;
let adj = Array.from({ length: V }, () => []);
adj[1].push(0);
adj[0].push(1);
adj[0].push(2);
adj[2].push(0);
adj[1].push(2);
adj[2].push(1);
console.log(isCyclic(V, adj) ? "Contains cycle" : "No Cycle");
V = 3;
let adj2 = Array.from({ length: V }, () => []);
adj2[0].push(1);
adj2[1].push(0);
adj2[1].push(2);
adj2[2].push(1);
console.log(isCyclic(V, adj2) ? "Contains Cycle" : "No Cycle");
OutputContains cycle
No Cycle
Time Complexity: O(V+E), The program does a simple DFS Traversal of the graph which is represented using an adjacency list. So the time complexity is O(V+E).
Auxiliary Space: O(V)
Related Articles: