Python Connected Components边缘列表

时间:2017-02-15 13:54:11

标签: python algorithm edges

我在python中使用这些算法从边缘查找连接的组件。

components = []

def connected_components(pairs):
    for a, b in pairs:
        for component in components:
            if a in component:
                for i, other_component in enumerate(components):
                    if b in other_component and other_component != component: # a, and b are already in different components: merge
                        component.extend(other_component)
                        components[i:i+1] = []
                        break # we don't have to look for other components for b
                else: # b wasn't found in any other component
                    if b not in component:
                        component.append(b)
                break # we don't have to look for other components for a
            if b in component: # a wasn't in in the component 
                component.append(a)
                break # we don't have to look further
        else: # neither a nor b were found
            components.append([a, b])
    return components

此算法返回如下组件:

[ [n1,n2,n4],[n3,n5] ]

我希望连接组件中的所有边列表如下:

[ [(n1,n2),(n2,n4),(n4,n1)],[(n3,n5)] ] 

与上一个列表的顺序相同,但我不知道如何创建此列表

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

注意:这并不需要任何python依赖。

我将通过递归深度优先搜索分享我的方法。我假设图是双向的,下面的代码可以很容易地操纵有向图。

pairs = [] // edge list
adj_list = {} // adjacency list
vis = [] // visited_list
connected_components = [] // contains all the connected components
temp_component = [] 

// basic depth first search
def dfs( node ):
     vis[node] = "true"
     temp_component.append(node)
     for neighbour in adj_list[node]:
       if vis[neighbour] == "false":
          dfs(neigbour)

//main
for a,b in pairs:
 if a not in adj_list:
  adj_list[a] = [] 
 if b not in adj_list:
  adj_list[b] = []
 adj_list[a].append(b)
 adj_list[b].append(a)
 vis["a"] = "false"
 vis["b"] = "false" 

for a,b in pairs:
  temp_component = []
  if vis[a] == "false":
   dfs(a)
 if len(temp_component) > 0:
   connected_components.append(temp_component)

 // once you have connected components you can get the edge lists in connected component as well
 answer = [] 
 for component in connected_components:
    temp_pairs = [] // contains the pair of edges for the current connected component
     for node in component:
        for i,j in pairs: 
          if (node == i or node == j) and (i,j) not in temp_node: 
              temp_node.append(i,j)
     answer.append(temp_pairs) 

答案 1 :(得分:0)

使用apgl库在python中创建一个迷你图。 您可以使用apgl中的SparseGraph模块。 from apgl.graph import SparseGraph

启动一个包含所需节点数的稀疏图。 graph = SparseGraph(num_vertices)

然后,您可以通过在图形节点之间添加边来创建迷你图形。 graph.addEdge(component1, component2)

然后只需使用findConnectedComponents函数查找连接的组件。 graph.findConnectedComponents()