The Wayback Machine - https://web.archive.org/web/20250328090153/https://www.geeksforgeeks.org/detect-cycle-undirected-graph/
Open In App

Detect cycle in an undirected graph

Last Updated : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an undirected graph, the task is to check if there is a cycle in the given graph.

Examples:

Input: V = 4, E = 4

Input-Undirected-Graph

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

Input-Undirected-Graph-2

Undirected graph with 4 vertices and 3 edges

Output: No 
Explanation: There is no cycle in the given graph.

Using Breadth First Search – O(V+E) time and O(V) space

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 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 <iostream>
#include <vector>
using namespace std;

// A recursive function that
// uses visited[] and parent to detect
// cycle in subgraph reachable
// from vertex v.
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;
}

// Returns true if the graph contains
// a cycle, else false.
bool isCycle(vector<vector<int>>& adj) {
    int V = adj.size();
    
    // Mark all the vertices as not visited
    vector<bool> visited(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 (isCycleUtil(u, adj, visited, -1))
                return true;
    }
    
    return false;
}

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);

    if (isCycle(adj)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }

    return 0;
}
Java
// A Java Program to detect
// cycle in an undirected graph

import java.util.ArrayList;

class GfG {

    // A recursive function that
    // uses visited[] and parent to detect
    // cycle in subgraph reachable
    // from vertex v.
    static boolean isCycleUtil(int v, ArrayList<ArrayList<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 (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;
    }

    // Returns true if the graph contains
    // a cycle, else false.
    static boolean isCycle(ArrayList<ArrayList<Integer>> adj) {
        int V = adj.size();
        
        // 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 (isCycleUtil(u, adj, visited, -1))
                    return true;
        }
        
        return false;
    }

    public static void main(String[] args) {
        int V = 3;
        ArrayList<ArrayList<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);

        if (isCycle(adj)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
# A Python Program to detect
# cycle in an undirected graph

def isCycleUtil(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 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.
        elif i != parent:
            return True
    
    return False

# Returns true if the graph contains
# a cycle, else false.
def isCycle(adj):
    V = len(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 isCycleUtil(u, adj, visited, -1):
                return True
    
    return False

if __name__ == "__main__":
    V = 3
    adj = [[] for _ in range(V)]

    adj[1].append(0)
    adj[0].extend([1, 2])
    adj[2].extend([0, 1])
    adj[1].append(2)

    if isCycle(adj):
        print("Yes")
    else:
        print("No")
C#
// A C# Program to detect
// cycle in an undirected graph

using System;
using System.Collections.Generic;

class GfG {

    // A recursive function that
    // uses visited[] and parent to detect
    // cycle in subgraph reachable
    // from vertex v.
    static bool isCycleUtil(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 (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;
    }

    // Returns true if the graph contains
    // a cycle, else false.
    static bool isCycle(List<List<int>> adj) {
        int V = adj.Count;
        
        // 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 (isCycleUtil(u, adj, visited, -1))
                    return true;
        }
        
        return false;
    }

    static void Main(string[] args) {
        int V = 3;
        List<List<int>> adj = new List<List<int>>();

        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);

        if (isCycle(adj)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// A JavaScript Program to detect
// cycle in an undirected graph

function isCycleUtil(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 (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;
}

// Returns true if the graph contains
// a cycle, else false.
function isCycle(adj) {
    const V = adj.length;
    
    // 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 (isCycleUtil(u, adj, visited, -1))
                return true;
    }
    
    return false;
}

const V = 3;
const adj = Array.from({length: V}, () => []);

adj[1].push(0);
adj[0].push(1, 2);
adj[2].push(0, 1);
adj[1].push(2);

if (isCycle(adj)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

Related Articles:



Next Article

Similar Reads

three90RightbarBannerImg