Connected Components
Given n nodes (0-indexed) and a list of undirected edges, return the number of connected components in the graph.
Implement count_components(n, edges), where n is the number of nodes and edges is a list of [a, b] pairs (empty if there are no edges). Return the count as an integer.
In the example below, the first line is n and the second line lists the edges as a,b pairs separated by semicolons.
Example
5 0,1;1,2;3,4
2
n=5means the graph has nodes . The sample edges are the pairs , and ; each edge is undirected, so it can be walked in either direction.- A connected component is a largest possible group of nodes in which every node can reach every other by following edges. Reachability chains: has no direct edge to , but links them, so is one group.
- Nodes and share an edge, giving the group . No edge touches both groups, so neither can grow further.
- Every node lands in exactly one group, and there are groups, so the output is
2. - Notice that only connectivity matters, not how many edges there are: adding an edge would leave the answer at
2, while a single edge would merge everything into1. A node with no edges at all still counts as its own component, son=3with no edges gives3.
Constraints
- 1 <= n <= 2000
- 0 <= edges <= 5000