美文网首页
数据结构(六)UnionFind

数据结构(六)UnionFind

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-08-14 03:08 被阅读0次

之前面试蘑菇街GG了,竟然是因为不懂UnionFind,来总结一下下啦。

def UnionFind(m, L):
    temp = [i for i in range(m)]
    for a, b in L:
        if temp[a-1] == temp[b-1]:
            continue
        temp_a, temp_b = temp[a-1], temp[b-1]  #这里是个坑,一定要这么写
        for i in range(len(temp)):
            if temp[i] == temp_b:
                temp[i] = temp_a
    return len(set(temp))

用BFS也是可以的啦~

import collections
def UnionFind2(m, L):
    mydic = collections.defaultdict(list)
    for a,b in L:
        mydic[a].append(b)
        mydic[b].append(a)
    res = 0
    visited = [0 for _ in range(m)]
    for i in range(1,m+1):
        if i in mydic and not visited[i-1]:
            res += 1
            BFS(mydic, visited, i)
            print(i,res,visited)
    return res + m - sum(visited)
def BFS(mydic, visited, index):
    qu = [index]
    while qu:
        people = qu.pop(0)
        visited[people-1] = 1
        for f in mydic[people]:
            if not visited[f-1]:
                visited[people-1] = 1
                qu.append(f)

相关文章

  • 数据结构(六)UnionFind

    之前面试蘑菇街GG了,竟然是因为不懂UnionFind,来总结一下下啦。 用BFS也是可以的啦~

  • LeetCode并查集(UnionFind)小结

    一,概述 并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets UnionFind)的...

  • 并查集UnionFind

    并查集(UnionFind)主要是用来解决图论中「动态连通性」问题的,数据结构很简单,却能用来表示无向图。简单的代...

  • 数据结构-并查集 UnionFind

    并查集定义: 并查集是一种树型的数据结构,用于处理一些不相交集合的合并及查询问题。常常在使用中以森林来表示。 并...

  • nodejs 并查集

    function UnionFind(row, col, idx){ var o = new Object(); ...

  • UnionFind count islands

    Question quoted from lintcode Given a n,m which means the...

  • 神奇的UnionFind (1)

    今天学习了神奇的并查集,UnionFind,试着做了几道之前用BFS/DFS的算法题,感觉超好用! UnionFi...

  • 并查集 - UnionFind

    基本概念 并查集能高效的查找两个元素是否在一个集合,而且能高效的合并两个集合。 使用树结构(Tree)来表示集合元...

  • 算法与数据结构(2),Map

    算法与数据结构(1),List 算法与数据结构(2),Map 算法与数据结构(3),并发结构 睡了不到六个小时,被...

  • 算法与数据结构(六):堆排序

    title: 算法与数据结构(六):堆排序tags: [算法与数据结构, C语言, 堆排序]date: 2019-...

网友评论

      本文标题:数据结构(六)UnionFind

      本文链接:https://www.haomeiwen.com/subject/eiwzwqtx.html