If I have an undirected graph (implemented as a list of vertices), how can I find its connected components? How can I use quick-union?
Perform depth-first search on the reversed graph. Start from the top vertex of the stack. Traverse through all of its child vertices. Once the already visited vertex is reached, one strongly connected component is formed.
Begin at any arbitrary node of the graph, G. Proceed from that node using either depth-first or breadth-first search, counting all nodes reached. Once the graph has been entirely traversed, if the number of nodes counted is equal to the number of nodes of G, the graph is connected; otherwise it is disconnected.
Use depth-first search (DFS) to mark all individual connected components as visited:
dfs(node u)
for each node v connected to u :
if v is not visited :
visited[v] = true
dfs(v)
for each node u:
if u is not visited :
visited[u] = true
connected_component += 1
dfs(u)
The best way is to use this straightforward method which is linear time O(n).
Since you asked about the union-find algorithm:
for each node parent[node] = node
for each node u :
for each node v connected to u :
if findset(u)!=findset(v) :
union(u,v)
**I assume you know about how findset and union works **
for each node if (parent[node] == node)
connected_component += 1
For every edge(u,v)
find union(u,v)
using quick union-find datastructure and find set of each vertex using find(v)
. Each new set is a connected component in the graph
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With