📘
Connected Components
Given n nodes (0-indexed) and a list of undirected edges, return the number of connected components in the graph.
Input: first line is n, second line is edges as a,b pairs separated by semicolons (empty if no edges).
Example:
Input:
5 0,1;1,2;3,4
Output:
2
Reasoning:
- The input
5represents the number of nodes in the graph, and the edges are given as0,1;1,2;3,4, which can be split into pairs:(0,1),(1,2), and(3,4). - These edges form two connected components: one containing nodes
0,1, and2, and another containing nodes3and4. - Node
4is connected to node3, but there are no edges connecting the first group of nodes (0,1,2) to the second group (3,4), resulting in 2 separate components. - The final output is the number of these connected components, which is 2.
Constraints:
- 1 <= n <= 2000
- 0 <= edges <= 5000
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.