Detect cycle in an undirected graph
Last Updated :
23 Jul, 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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem