A connected component is a group of nodes that can all reach each other. Counting components is the simplest complete graph algorithm: an outer loop over every node, and an inner search that swallows everything reachable.
A school's n computers, numbered 0 .. n-1, are joined by the network cables listed in edges; each [u, v] is one cable and works in both directions. Computers that can reach each other through cables form one cluster. Write count_components(n, edges) that returns how many separate clusters there are; a computer with no cable at all is a cluster on its own.
Examples
Input: n = 6, edges = [[0, 3], [3, 5], [1, 4]]
Output: 3
Explanation: {0, 3, 5}, {1, 4} and {2}; node 2 has no edges, so it is a component on its own
Input: n = 4, edges = [[2, 0], [1, 3], [0, 3]]
Output: 1
Constraints
1 <= n <= 20000 <= len(edges) <= 5000, no duplicate edges- Target: O(n + E) time
Goals
- Traverse a graph with DFS or BFS using a visited set
- Use the 'start a new search from every unvisited node' loop to count components
- Build an adjacency list from an edge list as a first step