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

PythonServer Side ProgrammingProgramming

When it is required to find all the connected components using depth first search in an undirected graph, a class is defined that contains methods to initialize values, perform depth first search traversal, find the connected components, add nodes to the graph and so on. The instance of the class can be created and the methods can be accessed and operations and be performed on it.

Below is a demonstration of the same −

## Example

Live Demo

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

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

visited[v] = True

temp.append(v)

if visited[i] == False:
temp = self.DFS_Utililty(temp, i, visited)
return temp

def connected_components(self):
visited = []
conn_compnent = []
for i in range(self.V):
visited.append(False)
for v in range(self.V):
if visited[v] == False:
temp = []
conn_compnent.append(self.DFS_Utililty(temp, v, visited))
return conn_compnent

my_instance = Graph_struct(5)
print("1-->0")
print("2-->3")
print("3-->0")
conn_comp = my_instance.connected_components()
print("The connected components are :")
print(conn_comp)

## Output

1-->0
2-->3
3-->0
The connected components are :
[[0, 1, 3, 2], [4]]

## Explanation

• A class named ‘Graph_struct’ is defined.

• A method named ‘add_edge’ is defined that helps add elements to the tree.

• The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach.

• A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other.

• An instance of the class is created, and the methods are called on it.

• The node are displayed on the console.

• The connected components are displayed as output on the console.

Published on 17-Apr-2021 11:55:42