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

Connected components in an undirected graph are maximal sets of vertices where every vertex is reachable from every other vertex in the same component. This article demonstrates finding all connected components using BFS (Breadth-First Search) traversal.

Understanding Connected Components

A connected component is a subgraph where:

  • Every vertex can reach every other vertex in the component
  • No vertex in the component can reach vertices outside it
  • The component cannot be extended by adding more vertices

BFS Implementation for Connected Components

Here's how to find all connected components using BFS traversal ?

from collections import deque

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

    def add_edge(self, u, v):
        """Add an edge between vertices u and v"""
        self.adj[u].append(v)
        self.adj[v].append(u)

    def bfs_component(self, start, visited):
        """BFS to find all vertices in one connected component"""
        queue = deque([start])
        visited[start] = True
        component = []
        
        while queue:
            vertex = queue.popleft()
            component.append(vertex)
            
            # Visit all adjacent vertices
            for neighbor in self.adj[vertex]:
                if not visited[neighbor]:
                    visited[neighbor] = True
                    queue.append(neighbor)
        
        return component

    def find_connected_components(self):
        """Find all connected components in the graph"""
        visited = [False] * self.V
        components = []
        
        for vertex in range(self.V):
            if not visited[vertex]:
                component = self.bfs_component(vertex, visited)
                components.append(component)
        
        return components

# Create graph with 6 vertices
graph = Graph(6)

# Add edges
graph.add_edge(0, 1)
graph.add_edge(0, 5)
graph.add_edge(2, 3)
graph.add_edge(3, 4)

print("Graph edges:")
print("0 -- 1")
print("0 -- 5") 
print("2 -- 3")
print("3 -- 4")
print()

# Find connected components
components = graph.find_connected_components()
print("Connected components found:")
for i, component in enumerate(components, 1):
    print(f"Component {i}: {component}")
Graph edges:
0 -- 1
0 -- 5
2 -- 3
3 -- 4

Connected components found:
Component 1: [0, 1, 5]
Component 2: [2, 3, 4]

How BFS Works for Connected Components

The algorithm works as follows:

  1. Initialize: Create a visited array to track processed vertices
  2. Iterate: For each unvisited vertex, start a new BFS
  3. BFS Traversal: Use a queue to visit all reachable vertices
  4. Component Formation: All vertices visited in one BFS form one component

Visual Representation

0 1 5 2 3 4 Component 1: {0, 1, 5} Component 2: {2, 3, 4}

Time and Space Complexity

Aspect Complexity Explanation
Time O(V + E) Visit each vertex once, traverse each edge once
Space O(V) Visited array and BFS queue storage

Key Differences: BFS vs DFS

Algorithm Data Structure Traversal Order Space Usage
BFS Queue Level by level O(V) for queue
DFS Stack (recursion) Depth first O(V) for recursion stack

Conclusion

BFS provides an effective way to find connected components by exploring vertices level by level. Both BFS and DFS have the same time complexity O(V + E), but BFS uses a queue for iterative traversal while DFS typically uses recursion.

Updated on: 2026-03-25T19:12:28+05:30

781 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements