在图中查找连接的组件 [英] Find connected components in a graph

查看:30
本文介绍了在图中查找连接的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个无向图(实现为顶点列表),我怎样才能找到它的连通分量?如何使用快速联合?

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?

推荐答案

使用深度优先搜索 (DFS) 将所有单独的连接组件标记为已访问:

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)

最好的方法是使用这种简单的方法,即线性时间 O(n).
由于您询问了联合查找算法:

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

这篇关于在图中查找连接的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆