AlgoFrames

Count components

Standard · Write code · about 12 min

An undirected graph has n nodes numbered 0 to n - 1 and a list of edges. Return the number of connected components.

A node with no edges is a component by itself.

Example 1

Input:

[{"n":5,"edges":[[0,1],[1,2],[3,4]],"directed":false}]

Output:

2

Nodes 0 to 2 and nodes 3 and 4.

Example 2

Input:

[{"n":4,"edges":[],"directed":false}]

Output:

4

No edges: every node is alone.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ edges ≤ 2000
  • Every edge joins two different nodes, and an edge may appear twice

Learn the idea first: Connected components and flood fill, a visual lesson.

More Connected components and flood fill problems