Connected Components in Undirected Graph
BFS — Component Discovery
LeetCode 323 • Medium • Graphs
Input: n = 5, edges = [[0,1],[1,2],[3,4]] → Output: 2
For each unvisited node, run BFS to discover its entire connected component. Count how many BFS calls it takes.
Time
O(V+E)
visit each vertex & edge once
Space
O(V)
visited set + queue
Visited: 0/5
Queue: 0
Components: 0
Processing
In Queue
Component 1
Component 2
Unvisited
Queue
empty
Visited
{ }
Count
0
Ready
Press Play to watch BFS discover connected components, or Step to advance one operation at a time.
Each unvisited node triggers a new BFS, discovering one complete component.
Each unvisited node triggers a new BFS, discovering one complete component.