Number of Connected Components in an Undirected Graph
Problem statement
You are given an undirected graph with n vertices labeled from 0 to n - 1 and an edge list edges. Return the number of connected components in the graph.
Function
countComponents(n: int, edges: int[][]) → intExamples
Example 1
n = 5edges = [[0,1],[1,2],[3,4]]return = 2The components are {0,1,2} and {3,4}.
Example 2
n = 5edges = [[0,1],[1,2],[2,3],[3,4]]return = 1Every vertex is connected through one chain.
Example 3
n = 4edges = []return = 4With no edges, each vertex forms its own component.
Constraints
1 <= n <= 2000.0 <= edges.length <= 5000.edges[i].length = 2.0 <= edges[i][0], edges[i][1] < n.- There are no self-loops or duplicate edges.