Python连接组件

feg*_*ege 7 python graph-algorithm connected-components

我正在get_connected_components为一个类写一个函数Graph:

def get_connected_components(self):
    path=[]
    for i in self.graph.keys():
        q=self.graph[i]
        while q:
            print(q)
            v=q.pop(0)
            if not v in path:
                path=path+[v]
    return path
Run Code Online (Sandbox Code Playgroud)

我的图是:

{0: [(0, 1), (0, 2), (0, 3)], 1: [], 2: [(2, 1)], 3: [(3, 4), (3, 5)], \
4: [(4, 3), (4, 5)], 5: [(5, 3), (5, 4), (5, 7)], 6: [(6, 8)], 7: [], \
8: [(8, 9)], 9: []}
Run Code Online (Sandbox Code Playgroud)

其中键是节点,值是边缘.我的函数给了我这个连接组件:

[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), \
(5, 4), (5, 7), (6, 8), (8, 9)]
Run Code Online (Sandbox Code Playgroud)

但我会有两个不同的连接组件,如:

[[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), \
(5, 3), (5, 4), (5, 7)],[(6, 8), (8, 9)]]
Run Code Online (Sandbox Code Playgroud)

我不明白我犯了什么错误.谁能帮我?

pil*_*her 14

我喜欢这个算法:

def connected_components(neighbors):
    seen = set()
    def component(node):
        nodes = set([node])
        while nodes:
            node = nodes.pop()
            seen.add(node)
            nodes |= neighbors[node] - seen
            yield node
    for node in neighbors:
        if node not in seen:
            yield component(node)
Run Code Online (Sandbox Code Playgroud)

它不仅短而优雅,而且速度快.像这样使用它(Python 2.7):

old_graph = {
    0: [(0, 1), (0, 2), (0, 3)],
    1: [],
    2: [(2, 1)],
    3: [(3, 4), (3, 5)],
    4: [(4, 3), (4, 5)],
    5: [(5, 3), (5, 4), (5, 7)],
    6: [(6, 8)],
    7: [],
    8: [(8, 9)],
    9: []}

new_graph = {node: set(each for edge in edges for each in edge)
             for node, edges in old_graph.items()}
components = []
for component in connected_components(new_graph):
    c = set(component)
    components.append([edge for edges in old_graph.values()
                            for edge in edges
                            if c.intersection(edge)])
print components
Run Code Online (Sandbox Code Playgroud)

结果是:

[[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), (5, 4), (5, 7)],
 [(6, 8), (8, 9)]]
Run Code Online (Sandbox Code Playgroud)


jim*_*iki 5

让我们简化图形表示:

myGraph = {0: [1,2,3], 1: [], 2: [1], 3: [4,5],4: [3,5], 5: [3,4,7], 6: [8], 7: [],8: [9], 9: []}
Run Code Online (Sandbox Code Playgroud)

这里我们有函数返回一个字典,它的键是根,其值是连接的组件:

def getRoots(aNeigh):
    def findRoot(aNode,aRoot):
        while aNode != aRoot[aNode][0]:
            aNode = aRoot[aNode][0]
        return (aNode,aRoot[aNode][1])
    myRoot = {} 
    for myNode in aNeigh.keys():
        myRoot[myNode] = (myNode,0)  
    for myI in aNeigh: 
        for myJ in aNeigh[myI]: 
            (myRoot_myI,myDepthMyI) = findRoot(myI,myRoot) 
            (myRoot_myJ,myDepthMyJ) = findRoot(myJ,myRoot) 
            if myRoot_myI != myRoot_myJ: 
                myMin = myRoot_myI
                myMax = myRoot_myJ 
                if  myDepthMyI > myDepthMyJ: 
                    myMin = myRoot_myJ
                    myMax = myRoot_myI
                myRoot[myMax] = (myMax,max(myRoot[myMin][1]+1,myRoot[myMax][1]))
                myRoot[myMin] = (myRoot[myMax][0],-1) 
    myToRet = {}
    for myI in aNeigh: 
        if myRoot[myI][0] == myI:
            myToRet[myI] = []
    for myI in aNeigh: 
        myToRet[findRoot(myI,myRoot)[0]].append(myI) 
    return myToRet  
Run Code Online (Sandbox Code Playgroud)

让我们试试看:

print getRoots(myGraph)
Run Code Online (Sandbox Code Playgroud)

{8: [6, 8, 9], 1: [0, 1, 2, 3, 4, 5, 7]}


Mat*_*yer 5

前面的答案很棒。不管怎样,我花了一点时间才明白发生了什么事。因此,我以这种更易于阅读的方式重构了代码。我将代码留在这里,以防有人发现它也更容易(它在 python 3.6 中运行)

def get_all_connected_groups(graph):
    already_seen = set()
    result = []
    for node in graph:
        if node not in already_seen:
            connected_group, already_seen = get_connected_group(node, already_seen)
            result.append(connected_group)
    return result


def get_connected_group(node, already_seen):
        result = []
        nodes = set([node])
        while nodes:
            node = nodes.pop()
            already_seen.add(node)
            nodes = nodes or graph[node] - already_seen
            result.append(node)
        return result, already_seen


graph = {
     0: {0, 1, 2, 3},
     1: set(),
     2: {1, 2},
     3: {3, 4, 5},
     4: {3, 4, 5},
     5: {3, 4, 5, 7},
     6: {6, 8},
     7: set(),
     8: {8, 9},
     9: set()}

components = get_all_connected_groups(graph)
print(components)
Run Code Online (Sandbox Code Playgroud)

结果:

Out[0]: [[0, 1, 2, 3, 4, 5, 7], [6, 8, 9]] 
Run Code Online (Sandbox Code Playgroud)

另外,我简化了输入和输出。我认为打印组中的所有节点会更清楚一些

  • “nodes = 节点或 graph[node] - already_seen”应该是“nodes.update(graph[node] - has_seen)” (3认同)