Number of Connected Components In An Undirected Graph
Return the number of connected components in an undirected graph with n nodes labeled 0..n-1, including isolated nodes.
Example 1
n = 5
edges = [[0,1],[1,2],[3,4]]2Explanation
0,1,2 form one component and 3,4 another.
Example 2
n = 4
edges = []4Explanation
With no edges all four nodes are isolated components.
Example 3
n = 3
edges = [[0,1],[1,2],[0,2]]1Explanation
All three nodes are connected despite their cycle, giving one component.
Constraints
- 1 <= n <= 2000
- Edges are distinct valid unordered pairs without self-loops
Function contract
countComponentsArguments: json, jsonSolutionRuns on your device
Loading draft…
Run: 3 examples; Submit: 35 cases, on your device.
5[[0,1],[1,2],[3,4]]