Counting Connected Components
Start a new traversal at each still-unvisited vertex to discover another component.
Core Intuition & How It Works
Counting connected components in an undirected graph iterates over every vertex and launches a BFS or DFS whenever an unvisited vertex is found. Each launch explores one complete component, visiting every vertex and edge once.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(V + E) |
| Space Complexity | O(V) |
| Topic Chapter | Chapter 11: Graph Traversal & Connectivity |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Loop over all vertices 0..V-1 rather than starting from node 0 alone so isolated vertices and disconnected clusters are counted.
Common Pitfalls & Edge Cases
Assuming an undirected graph is connected from a single traversal, or confusing undirected components with directed SCCs.
Real-World & Technical Interview Applications
Number of islands in grids, network partition detection, image region labeling, and friend-circle clustering.