323. Number of Connected Components in an Undirected Graph
Last updated
Was this helpful?
Last updated
Was this helpful?
Givenn
nodes labeled from0
ton - 1
and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
Givenn = 5
andedges = [[0, 1], [1, 2], [3, 4]]
, return2
.
Example 2:
Givenn = 5
andedges = [[0, 1], [1, 2], [2, 3], [3, 4]]
, return1
.
Thoughts:
Connected graph: add new edge to merge (make less) components if no cycle after being added is introduced-> union find: using an array to map each nodes's root value to detect cycle.
Time: O(n*len(edges)). space(n)
Very similar to
Code:
Code (Java):