Python Program to Find if Undirected Graph contains Cycle using BFS

PythonServer Side ProgrammingProgramming

When it is required to find the sum of all the nodes of a tree, a class is created, and it contains methods to set the root node, add elements to the tree, search for a specific element, and add elements of the tree to find the sum and so on. An instance of the class can be created to access and use these methods.

Below is a demonstration of the same −

Example

 Live Demo

from collections import deque

def add_edge(adj: list, u, v):
   adj[u].append(v)
   adj[v].append(u)

def detect_cycle(adj: list, s, V, visited: list):

   parent = [-1] * V

   q = deque()

   visited[s] = True
   q.append(s)

   while q != []:

      u = q.pop()

      for v in adj[u]:
         if not visited[v]:
            visited[v] = True
            q.append(v)
            parent[v] = u
         elif parent[u] != v:
            return True
   return False

def cycle_disconnected(adj: list, V):

   visited = [False] * V

   for i in range(V):
      if not visited[i] and detect_cycle(adj, i, V, visited):
         return True
   return False

if __name__ == "__main__":
   V = 5
   adj = [[] for i in range(V)]
   add_edge(adj, 0, 1)
   add_edge(adj, 1, 2)
   add_edge(adj, 2, 0)
   add_edge(adj, 2, 3)
   add_edge(adj, 2, 1)

   if cycle_disconnected(adj, V):
      print("There are 5 vertices in the graph")
      print("0-->1")
      print("1-->2")
      print("2-->0")
      print("2-->3")
      print("2-->1")
      print("Is there a cycle ?")
      print("Yes")
   else:
      print("There are 5 vertices in the graph")
      print("0-->1")
      print("1-->2")
      print("2-->0")
      print("2-->3")
      print("2-->1")
      print("Is there a cycle ?")
      print("Yes")
      print("No")

Output

There are 5 vertices in the graph
0-->1
1-->2
2-->0
2-->3
2-->1
Is there a cycle ?
Yes

Explanation

  • The required packages are imported.

  • Another method named ‘add_edge’ is defined that helps add nodes to the graph.

  • A method named ‘detect_cycle’ is defined that helps determine if a cycle is formed when the components of the graph are connected.

  • Another method named ‘cycle_disconnected’ is defined that helps determine if the cycle is a connected one or not.

  • Elements are added to graph using the ‘add_edge’ method.

  • It is displayed on the console.

  • The ‘cycle_disconnected’ method is called and the output is displayed on the console.

raja
Published on 17-Apr-2021 15:19:48
Advertisements