📘
Number of Connected Components
MediumGraphs
Given n nodes (0 to n-1) and undirected edges, return the number of connected components.
Input: first line = n, second = edges as u:v comma-separated (or 'none').
Example:
Input:
5 0:1,1:2,3:4
Output:
2
Reasoning:
- The input
5represents the number of nodes (n=5) in the graph. - The edges
0:1,1:2,3:4are used to create an adjacency list, showing that nodes 0, 1, and 2 are connected, as well as nodes 3 and 4. - We identify the connected components by traversing the graph: one component contains nodes 0, 1, and 2, and another contains nodes 3 and 4.
- The number of connected components is then counted, resulting in a total of 2 components.
- The final output is therefore 2.
Constraints:
- 1 <= n <= 2000
- 0 <= number of edges <= 5000
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.