Python Program to Find All Connected Components using BFS in an Undirected Graph


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

class Graph_structure:

   def __init__(self, V):
      self.V = V
      self.adj = [[] for i in range(V)]

   def DFS_Utility(self, temp, v, visited):

      visited[v] = True

      temp.append(v)

      for i in self.adj[v]:
         if visited[i] == False:

            temp = self.DFS_Utility(temp, i, visited)
      return temp

   def add_edge(self, v, w):
      self.adj[v].append(w)
      self.adj[w].append(v)

   def find_connected_components(self):
      visited = []
      connected_comp = []
      for i in range(self.V):
         visited.append(False)
      for v in range(self.V):
         if visited[v] == False:
            temp = []
            connected_comp.append(self.DFS_Utility(temp, v, visited))
      return connected_comp

my_instance = Graph_structure(6)
my_instance.add_edge(1, 0)
my_instance.add_edge(2, 3)
my_instance.add_edge(3, 4)
my_instance.add_edge(5, 0)
print("There are 6 edges. They are : ")
print("1-->0")
print("2-->3")
print("3-->4")
print("5-->0")

connected_comp = my_instance.find_connected_components()
print("The connected components are...")
print(connected_comp)

Output

There are 6 edges. They are :
1-->0
2-->3
3-->4
5-->0
The connected components are...
[[0, 1, 5], [2, 3, 4]]

Explanation

  • A class named ‘Graph_structure’ is defined, with the ‘_init_’ method.

  • A method named ‘DFS_Utility’ is defined that helps perform the depth first traversal on the elements of the graph.

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

  • Another method named ‘find_connected_components’ is defined that helps determine the nodes connected to a specific node.

  • An instance of the ‘Graph_structure’ is created.

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

  • It is displayed on the console.

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

Updated on: 17-Apr-2021

530 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements