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日)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值