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

Detect cycle in an undirected graph

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
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.

Find cycle in Undirected Graph using BFS:

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

Output
Contains 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:



Previous Article
Next Article

Similar Reads

Detect cycle in an undirected graph using BFS
Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle of 1-0-2-1.  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirect
5 min read
What is Undirected Graph? | Undirected Graph meaning
An undirected graph is a type of graph where the edges have no specified direction assigned to the them. Characteristics of an Undirected Graph:Edges in an undirected graph are bidirectional in nature.In an undirected graph, there is no concept of a "parent" or "child" vertex as there is no direction to the edges.An undirected graph may contain loo
2 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Shortest cycle in an undirected unweighted graph
Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1. Examples: Input: Output: 4 Cycle 6 -> 1 -> 5 -> 0 -> 6 Input: Output: 3 Cycle 6 -> 1 -> 2 -> 6 Prerequisites: Dijkstra Approach: For every vertex, we check if it is possible to get the shor
8 min read
Minimum labelled node to be removed from undirected Graph such that there is no cycle
Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle. Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1. Examples: Input: N = 5, edges[][] = {{5, 1}, {5, 2}, {1, 2}, {2, 3}, {2, 4}} O
15+ min read
Check if a cycle exists between nodes S and T in an Undirected Graph with only S and T repeating
Given an undirected graph with N nodes and two vertices S & T, the task is to check if a cycle between these two vertices exists or not, such that no other node except S and T appear more than once in that cycle. Print Yes if it exists otherwise print No. Example: Input: N = 7, edges[][] = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 2}, {2, 6}
10 min read
Check if a cycle exists between nodes S and T in an Undirected Graph with only S and T repeating | Set - 2
Given an undirected graph with N nodes and two vertices S & T, the task is to check if a cycle between these two vertices exists (and return it) or not, such that no other node except S and T appears more than once in that cycle. Examples: Input: N = 7, edges[][] = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 2}, {2, 6}, {6, 0}}, S = 0, T = 4 O
12 min read
Check whether an undirected graph contains cycle or not
Given an undirected graph, the task is to check whether it has a cycle or not, and if it has a cycle return the vertices of the cycle. Examples: Input: Output: Cycle exists. 3 -> 2 -> 1Explanation: Cycle exists for 3 -> 2 ->1 Input: Output: Cycle does not exist. Approach: This problem can be solved using DFS of Graph and Stack to store
15 min read
Find minimum weight cycle in an undirected graph
Given a positive weighted undirected graph, find the minimum weight cycle in it. Examples: Minimum weighted cycle is : Minimum weighed cycle : 7 + 1 + 6 = 14 or 2 + 6 + 2 + 4 = 14 The idea is to use shortest path algorithm. We one by one remove every edge from the graph, then we find the shortest path between two corner vertices of it. We add an ed
15+ min read
Check if there is a cycle with odd weight sum in an undirected graph
Given a weighted and undirected graph, we need to find if a cycle exist in this graph such that the sum of weights of all the edges in that cycle comes out to be odd. Examples: Input : Number of vertices, n = 4, Number of edges, m = 4 Weighted Edges = 1 2 12 2 3 1 4 3 1 4 1 20 Output : No! There is no odd weight cycle in the given graph Input : Num
15+ min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directed Weighted Graph Using Bellman-Ford:Initialize dis
15+ min read
Detect cycle in Directed Graph using Topological Sort
Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -> V from vertex U to vertex V, U comes before V in the ordering. E
9 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Detect Cycle in a Directed Graph using BFS
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return true. Recommended: Please solve it on "PRACTICE" f
11 min read
Detect Cycle in Graph using DSU
Given an undirected graph, the task is to check if the graph contains a cycle or not, using DSU. Examples: Input: The following is the graph Output: YesExplanation: There is a cycle of vertices {0, 1, 2}. Recommended PracticeDetect Cycle using DSUTry It!We already have discussed an algorithm to detect cycle in directed graph. Here Union-Find Algori
13 min read
Detect Cycle in a directed graph using colors
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: Yes Explanation: This diagram clearly shows a cycle 0 -> 2 -> 0. Inpu
11 min read
Detect Cycle in a Directed Graph
Given the root of a Directed graph , The task is to check whether the graph contains a cycle or not. Examples: Input: V = 4, E = 6 Output: Yes Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0 Input: V = 4, E = 4 Output: No Explanation: The diagram clearly shows no cycle. Detect Cycle in a Directed Graph using DFS:The problem can be
14 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum
Given an array arr[] consisting of values of N vertices of an initially unconnected Graph and an integer M, the task is to connect some vertices of the graph with exactly M edges, forming only one connected component, such that no cycle can be formed and Bitwise AND of the connected vertices is maximum possible. Examples: Input: arr[] = {1, 2, 3, 4
9 min read
Detect Cycle in a 2D grid
Given a 2D grid arr[][] with different characters, the task is to detect whether it contains a cycle or not. A sequence of characters or integers c1, c2, .... cM is called a cycle if and only if it meets the following condition: M should at least be 4.All characters belong to the same character or integer. For all 0 <= i <= M -1 : ci and ci +
15 min read
Detect Cycle in a Linked List using Map
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List Example Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list. Input: 20-
7 min read
Detect loop or cycle in a linked list
Given a singly linked list, check if the linked list has a loop (cycle) or not. A loop means that the last node of the linked list is connected back to a node in the same list. Examples: Input: head: 1 -> 3 -> 4 -> NULL Output: true Input: head: 1 -> 8 -> 3 -> 4 -> NULL Output: false Table of Content [Naive Approach] Using Hash
13 min read
Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
Given an undirected graph having N vertices and M edges and each vertex is associated with a cost and a source vertex S is given. The task is to find the maximum cost path from source vertex S such that no edge is visited consecutively 2 or more times. Examples: Input: N = 5, M = 5, source = 1, cost[] = {2, 2, 8, 6, 9}, Below is the given graph: Ou
12 min read
Print all the cycles in an undirected graph
Given an undirected graph, print all the vertices that form cycles in it. Pre-requisite: Detect Cycle in a directed graph using colors In the above diagram, the cycles have been marked with dark green color. The output for the above will be 1st cycle: 3 5 4 6 2nd cycle: 5 6 10 93rd cycle: 11 12 13 Approach: Using the graph coloring method, mark all
11 min read
Product of lengths of all cycles in an undirected graph
Given an undirected and unweighted graph. The task is to find the product of the lengths of all cycles formed in it.Example 1: The above graph has two cycles of length 4 and 3, the product of cycle lengths is 12. Example 2: The above graph has two cycles of length 4 and 3, the product of cycle lengths is 12. Approach: Using the graph coloring metho
12 min read
Find if an undirected graph contains an independent set of a given size
Given an undirected graph, check if it contains an independent set of size k. Print 'Yes' if there exists an independent set of size k. Print 'No' otherwise. Independent Set: An independent set in a graph is a set of vertices that are not directly connected to each other. Example 1: Input : K = 4, graph = [[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1
10 min read
Kth largest node among all directly connected nodes to the given node in an undirected graph
Given two arrays u and v, representing a graph such that there is an undirected edge from u[i] to v[i] (0 ? v[i], u[i] < N) and each node has some value val[i] (0 ? i < N). For each node, if the nodes connected directly to it are sorted in descending order according to their values (in case of equal values, sort it according to their indices
7 min read
Find all cliques of size K in an undirected graph
Given an undirected graph with N nodes and E edges and a value K, the task is to print all set of nodes which form a K size clique. A clique is a complete subgraph of a graph.Examples: Input: N = 5, edges[] = { {1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 5}, {5, 3} }, K = 3 Output: 1 2 3, 3 4 5 Explanation: Clearly from the image, 1->2->3 and 3->4
11 min read
Count total ways to reach destination from source in an undirected Graph
Given an undirected graph, a source vertex ‘s’ and a destination vertex ‘d’, the task is to count the total paths from the given ‘s’ to ‘d’. Examples Input: s = 1, d = 4 Output: 2 Explanation: Below are the 2 paths from 1 to 4 1 -> 3 -> 4 1 -> 2 -> 3 -> 4 Input: s = 3, d = 9 Output: 6 Explanation: Below are the 6 paths from 3 to 9 3
12 min read