Understanding Count Connected Components
Count connected components in an undirected graph with vertices numbered 0 through n - 1.
How it works
Each edge joining two different roots merges exactly two components into one.
Start with every vertex in its own component. Follow parent links to find the two roots for each edge. Attach the smaller component to the larger and decrement the count.
Try an example
Input: n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output: 2
Each edge joining two different roots merges exactly two components into one.
Constraints
- n is an integer from 0 through 16; at most 48 edges [u, v].
- Every endpoint must be a valid vertex. Self-loops and repeated edges are allowed.
- An empty graph has zero components.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.