并查集原理并Python实现、Java实现

原文地址

分类目录——数据结构笔记

喔哈哈,刷题刷到了并查集,我就把我一年级时候的课程设计拿了出来,就直接贴上了

那会儿是用Java写的,Python实现放在了文尾

  • Python实现

    这里写了一份简单版的,通过字典实现父子关系relation = {son:father}

    # 构造{节点:祖先}关系,使每个节点的父亲都指向最顶层祖先
    def union_find(nodes, edges):
        father = {}  # 字典记录父节点 {node: father_node}
        for node in nodes:  # 初始化父亲为本身
            father[node] = node
    
        for edge in edges:  # 标记父节点
            fa, son = edge
            father[son] = fa
    
        for node in nodes:
            while True:  # 循环,直到找到根节点
                father_of_node = father[node]
                if father_of_node != father[father_of_node]:    # 找父节点的父节点(最父的节点的父节点是本身)
                    father[node] = father[father_of_node]
                else:  # 如果该节点的父节点与其爷爷节点相同,(上面的if为False,也就是此时,你懂得)
                    break  # 则说明找到了根节点
    
        return father
    
    # get环境中所有的族群(同一个祖先的为一个族群)
    def getpyq(nodes, edges):
        pyq = {}    # pyq=朋友圈
        relation_father = union_find(nodes, edges)
        for sub, root in relation_father.items():    # 经过上面的处理,这里root是祖先借点,每一个root形成一个族群
            # 根节点是key,子节点们组成的list是value
            if root not in pyq.keys():
                pyq[root] = [sub]
            else:
                pyq[root].append(sub)
        return pyq
    
    if __name__ == '__main__':
        nodes = list(range(0, 10))
        test_edges = [[0, 1], [0, 4], [1, 2], [1, 3], [5, 6], [6, 7], [7, 5], [8, 9]]
    
        father_relation = union_find(nodes, test_edges)
        print(father_relation)
        # {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 5, 6: 5, 7: 5, 8: 8, 9: 8}
    
        pyq = getpyq(nodes, test_edges)
        print(pyq)
        # {0: [0, 1, 2, 3, 4], 5: [5, 6, 7], 8: [8, 9]}
    
  • 参考文献

    部分参考并查集原理及Python实现,朋友圈个数问题

你可能感兴趣的:(Python,#,数据结构笔记)