Detect Cycle in a an Undirected Graph

To detect if there is any cycle in the undirected graph or not, we will use the DFS traversal for the given graph. For every visited vertex v, when we have found any adjacent vertex u, such that u is already visited, and u is not the parent of vertex v. Then one cycle is detected. 

We will assume that there are no parallel edges for any pair of vertices.

Input and Output:
Adjacency matrix
   
    0 1 0 0 0
    1 0 1 1 0
    0 1 0 0 1
    0 1 0 0 1
    0 0 1 1 0

Output:
The graph has cycle.

Algorithm

<strong>dfs</strong><strong>(vertex, visited, parent)</strong><p>
</p><p style=""><strong style="font-size: 14px; background-color: initial;">Input: </strong><span style="font-size: 14px; background-color: initial; text-align: initial;">The start vertex, the visited set, and the parent node of the vertex.</span></p><strong>Output: </strong>True a cycle is found.Begin
   add vertex in the visited set
   for all vertex v which is adjacent with vertex, do
      if v = parent, then
         return true
      if v is not in the visited set, then
         return true
      if dfs(v, visited, vertex) is true, then
         return true
   done
   return false
End hasCycle(graph)

<strong>Input: </strong>The given graph.

<strong>Output: </strong>True when a cycle has found.Begin
   for all vertex v in the graph, do
      if v is not in the visited set, then
         go for next iteration
      if dfs(v, visited, φ) is true, then     //parent of v is null
         return true
      return false
   done
End

Example

#include<iostream>
#include<set>
#define NODE 5
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 0, 0, 0},
   {1, 0, 1, 1, 0},
   {0, 1, 0, 0, 1},
   {0, 1, 0, 0, 1},
   {0, 0, 1, 1, 0}
};

bool dfs(int vertex, set<int>&visited, int parent) {
   visited.insert(vertex);
   for(int v = 0; v<NODE; v++) {
      if(graph[vertex][v]) {
         if(v == parent)    //if v is the parent not move that direction
            continue;
         if(visited.find(v) != visited.end())    //if v is already visited
            return true;
         if(dfs(v, visited, vertex))
            return true;
      }
   }
   return false;
}

bool hasCycle() {
   set<int> visited;       //visited set
   for(int v = 0; v<NODE; v++) {
      if(visited.find(v) != visited.end())    //when visited holds v, jump to next iteration
         continue;
      if(dfs(v, visited, -1)) {    //-1 as no parent of starting vertex
         return true;
      }
   }
   return false;
}

int main() {
   bool res;
   res = hasCycle();
   if(res)
      cout << "The graph has cycle." << endl;
   else
      cout << "The graph has no cycle." << endl;
}

Output

The graph has cycle.
Updated on: 2020-06-16T11:27:25+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements