Open In App

Detect cycle in an undirected graph

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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]]

Input-Undirected-Graph
Undirected Graph with 4 vertices and 4 edges

Output: true
Explanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0

Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]]

Input-Undirected-Graph-2
Undirected graph with 4 vertices and 3 edges

Output: 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");
}

Output
true

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:


Next Article

Similar Reads