Python算法教程:找出图的连通分量

一个图结构的连通分量是能让它里面的所有节点彼此到达的最大子图。

def components(graph):
    component = []
    seen = set()
    for u in graph:
        if u in seen:
            continue
        current = walk(graph, u)
        seen.update(current)
        component.append(current)
    return component


def walk(graph, start, s=set()):
    nodes, current = set(), dict()
    current[start] = None
    nodes.add(start)
    while nodes:
        u = nodes.pop()
        for v in graph[u].difference(current, s):
            nodes.add(v)
            current[v] = u
    return current


graph = {
    'a': set('bc'),
    'b': set('d'),
    'c': set('bd'),
    'd': set(),
}
print(components(graph))

(最近更新:2019年05月31日)

你可能感兴趣的:(PROGRAM)