Back to DSA

Number of Connected Components in an Undirected Graph

easy
Acceptance: 60%
GraphsUnion FindDFS

Given n nodes (labeled 0 to n-1) and a set of undirected edges, count how many separate connected components exist in the graph.

Examples

Example 1:
Input:n = 6, edges = [[0,1],[2,3],[4,5]]
Output:3
Explanation: Three pairs of connected nodes form three separate components.
Example 2:
Input:n = 4, edges = [[0,1],[1,2],[2,3]]
Output:1
Explanation: All four nodes are linked in a single chain.

Hints

00:00
1234567