Graph Cycle Detection Using DFS in C++

To detect a cycle in a graph using the Depth First Search(DFS) we can follow the below approach:

Approach

  • Start DFS traversal from any unvisited vertex on the graph.
  • Initialize a vector vis to keep track of the visited vertices during the traversal.
  • Mark the current vertex as visited.
  • For each adjacent vertex of the current vertex:
    • If the adjacent vertex is not visited , recursively call DFS on it with the current vertex as it’s parent.
    • If the adjacent vertex is visited, and it is not the parent of the current vertex, a cycle is detected. Return true.
  • If a cycle is not detected after the whole traversal of the graph return false.

C++ Program for Graph Cycle Detection using DFS

The following program illustrates how we can detect a cycle in an undirected graph using DFS:

C++
 // C++ Program for Graph Cycle Detection using DFS
#include <iostream>
#include <vector>
using namespace std;

// Define a class for representing an undirected graph
class Graph {
    
private:
 // Number of vertices in the graph
    int V;    
// Adjacency list representation of the graph
    vector<int>* adj;      
    
public:
    // Constructor to initialize the adjacency list for the graph
    Graph(int vertices) : V(vertices) {
        // Allocate memory for adjacency lists
        adj = new vector<int>[V];   
    }

    // Function to add an edge between two vertices in a graph
    void addEdge(int v, int w) {
        adj[v].push_back(w);    
        adj[w].push_back(v);    
    }

    // Depth-first search function to check for cycles
    bool dfs(int node, int parent, vector<bool>& vis) {
        vis[node] = true;   // Mark the current node as visited
        for (auto nbr : adj[node]) {
            if (!vis[nbr]) {
                // If the neighbor is not visited, recursively visit it
                if (dfs(nbr, node, vis)) return true;
            }
            else if (nbr != parent) {
                // If the neighbor is visited and not the parent, it forms a cycle
                return true;
            }
        }
        // If no cycle is found, return false
        return false;   
    }

    // Function to check if the graph contains a cycle
    bool isCycle() {
        // Initialize visited array with all vertices as not visited
        vector<bool> vis(V, false); 
        
        // Start DFS traversal from vertex 0
        bool cycle = dfs(0, -1, vis); 
        
        // Return true if cycle is found, false otherwise
        return cycle;
    }
};

// Driver Code
int main() {
    // Initialize a graph object having 4 vertices
    Graph g(4);

    // Adding edges to the graph
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(0, 3);
    g.addEdge(1, 2);

    // Check if the graph contains a cycle and print the result
    if (g.isCycle()) {
        cout << "Graph contains cycle" << endl;
    } else {
        cout << "Graph doesn't contain cycle" << endl;
    }

    return 0;
}

Output
Graph contains cycle

Time Complexity: O(V+E) where V represents the number of vertices and E represents the number of edges in the graph.
Auxiliary Space: O(V+E)

Graph Cycle Detection in C++

Detecting cycles in a graph is a crucial problem in graph theory that has various applications in fields like network analysis, databases, compilers, and many others. In this article, we will learn how to detect cycles in a graph in C++.

Similar Reads

Graph Cycle Detection in C++

A cycle in a graph is a path that starts and ends at the same vertex, with no repeated edges or vertices other than the first and the last vertex. Graphs containing cycles are called cyclic graphs. Let us consider the following undirected graph having 4 vertices:...

Graph Cycle Detection Using DFS in C++

To detect a cycle in a graph using the Depth First Search(DFS) we can follow the below approach:...

Graph Cycle Detection Using BFS

To detect a cycle in a graph using the Breadth First Search(BFS) we can follow the below approach:...