Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Detect cycle in an undirected graph
Next article icon

Detect cycle in an undirected graph

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Table of Content

  • Using Breadth First Search - O(V+E) time and O(V) space
  • Using Depth First Search - O(V+E) time and O(V) space

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:

  • cycle detection for directed graph
  • union-find algorithm for cycle detection in undirected graphs

Next Article
Detect cycle in an undirected graph

K

kartik
Improve
Article Tags :
  • Graph
  • DSA
  • Amazon
  • Adobe
  • Oracle
  • Flipkart
  • Samsung
  • MakeMyTrip
  • BFS
  • DFS
  • union-find
  • graph-cycle
Practice Tags :
  • Adobe
  • Amazon
  • Flipkart
  • MakeMyTrip
  • Oracle
  • Samsung
  • BFS
  • DFS
  • Graph
  • union-find

Similar Reads

    Depth First Search or DFS for a Graph
    In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
    13 min read

    DFS in different language

    C Program for Depth First Search or DFS for a Graph
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS tr
    4 min read
    Depth First Search or DFS for a Graph - Python
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a Boolean visited array. A graph can have more than one DFS tr
    4 min read
    Java Program for Depth First Search or DFS for a Graph
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Prerequisite: Graph knowledge is important to understand the concept of DFS. What is DFS?DFS or Depth First Traversal is the traversing algorithm. DFS can be used to approach the elements of a Graph. To avoid p
    3 min read
    Iterative Depth First Traversal of Graph
    Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
    10 min read
    Applications, Advantages and Disadvantages of Depth First Search (DFS)
    Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
    4 min read
    Difference between BFS and DFS
    Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
    2 min read
    Depth First Search or DFS for disconnected Graph
    Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Disconnected Graph Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given sour
    7 min read
    Printing pre and post visited times in DFS of a graph
    Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored
    8 min read
    Tree, Back, Edge and Cross Edges in DFS of Graph
    Given a directed graph, the task is to identify tree, forward, back and cross edges present in the graph.Note: There can be multiple answers.Example:Input: GraphOutput:Tree Edges: 1->2, 2->4, 4->6, 1->3, 3->5, 5->7, 5->8 Forward Edges: 1->8 Back Edges: 6->2 Cross Edges: 5-
    9 min read
    Transitive Closure of a Graph using DFS
    Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
    8 min read

    Variations of DFS implementations

    Implementation of DFS using adjacency matrix
    Depth First Search (DFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph.Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (wh
    8 min read
    Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
    We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and
    7 min read
    Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
    In Set 1, unweighted graph is discussed. In this post, weighted graph representation using STL is discussed. The implementation is for adjacency list representation of weighted graph. Undirected Weighted Graph We use two STL containers to represent graph: vector : A sequence container. Here we use i
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences