Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find connected components in a graph [closed]

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?

like image 391
abalcerek Avatar asked Jan 12 '14 18:01

abalcerek


People also ask

How do you find the strongly connected component of a graph?

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.

How do you find a connected graph?

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.


2 Answers

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
like image 101
Aseem Goyal Avatar answered Oct 25 '22 14:10

Aseem Goyal


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

like image 29
Vikram Bhat Avatar answered Oct 25 '22 15:10

Vikram Bhat