Skip to content
DeepForgeby svx
All problems
EasyGraph Algorithmsgraph-005

Connected Components Count

Problem

Count the connected components of an undirected graph with n nodes.

edges is a list of [u, v] pairs. Isolated nodes each form their own component.

Hint

Union endpoints together, then count distinct roots.

Test cases

case 1
in: [5,[[0,1],[1,2],[3,4]]]
expected: 2
case 2
in: [4,[]]
expected: 4
case 3
in: [1,[]]
expected: 1
case 4
in: [6,[[0,1],[1,2],[2,3],[3,4],[4,5]]]
expected: 1
Starter codePython
def count_components(n, edges):
    # Your code here
    pass

4 test cases · run your code against them in the editor