Number of Connected Components in an Undirected Graph
MediumAlgorithms
Description
You have a graph of `n` nodes labeled `0` to `n - 1`. You are given `n` and a list of `edges` where `edges[i] = [a, b]` is an undirected edge.
Return the number of **connected components** in the graph.
Example 1
Input:n = 5, edges = [[0,1],[1,2],[3,4]]
Output:2
Explanation:{0,1,2} and {3,4}.
Example 2
Input:n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output:1
Explanation:All nodes form one chain.
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= n * (n - 1) / 2
- There are no self-loops or repeated edges