Number of Connected Components
Number of Connected Components is a medium Graphs problem from the Blind 75. The key pattern is union-find or dfs, and a good solution runs in O(V + E) time.
Problem
Count connected components in an undirected graph with n labeled vertices.
Examples
Example 1
Input
{"n":6,"edges":[[0,1],[1,2],[3,4]]}Output
3Example 2
Input
{"n":5,"edges":[[0,4],[4,2],[1,3]]}Output
2Example 3
Input
{"n":5,"edges":[[0,1],[1,2],[2,3],[3,4]]}Output
1Approach
Start with n components and merge them edge by edge, or count how many traversals it takes to visit every vertex.
| Pattern | Union-find or DFS |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
Watch out for
Vertices with no edges are components too.