【问题标题】:Connected components of undirected graph无向图的连通分量
【发布时间】:2015-02-21 11:08:35
【问题描述】:

假设我有一个带有顶点 v1...vn 和边的无向图 G。现在它处于邻接表表示中。

对于每个时刻 a 都有一些此时“活动”的顶点子集作为输入。我需要在那个时间点找到这个顶点子集中的所有连接组件。

现在我已经使用联合查找数据结构实现了这一点,如下所示:

initialize sets for every active vertex so that every vertex has itself as "representative" (also called "parent")

for every active vertex v
   for all neighbours of v in G v_neighbour
      if v_neighbour is active
          union set of v and set of v_neighbour

应该没问题,但我想知道是否有更优化的方法? 该算法的运行时间是多少? O(N*M)?

【问题讨论】:

    标签: algorithm graph-algorithm


    【解决方案1】:

    BFSDFS 在连接组件耗尽后重新启动,可以在O(V+E) 的无向图中轻松找到所有连接组件

    connectedComponentNumber= 0
    While there is a node that was not discovered yet:
        connectedComponentNumber= connectedComponentNumber+ 1
        v = some vertex that was not discovered yet
        vertices = BFS(v) //all vertices connected to v
        set all nodes in vertices as belong to connected component connectedComponentNumber
    

    【讨论】:

    • 是的,谢谢你的建议。我现在正在实施迭代 DFS。它应该渐近更快。但我想强调一点,另一位程序员使用了某种带有递归的 DFS(虽然不是很优化),它比我的实现差得多。但我认为非递归优化版本应该可以正常工作。
    • @user1685095 递归与否,它是线性时间。无论您使用操作系统堆栈还是自定义堆栈数据结构,在实践中都应该没有真正的区别。也许该实现还有另一个问题,例如如何表示访问的顶点集或图本身。
    【解决方案2】:

    我想在上面的回复中添加一件事,如果您在邻接表表示中找到活动顶点,它将增加 V 步数,因此运行时间将增加到 O(V^3)。这可能需要恒定时间如果我们为此维护另一个数据结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多