PIXELBANKv8.2.1
Menu

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 5 represents the number of nodes (n=5n = 5) in the graph.
  • The edges 0:1,1:2,3:4 are 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 22 components.
  • The final output is therefore 22.

Constraints:

  • 1 <= n <= 2000
  • 0 <= number of edges <= 5000
Editor

Test Results

0/0
Run code to see test results.