Calcular los componentes conectados del conjunto de búsqueda combinado (python)

class UnionFind():
    def __init__(self):
        self.father = {
    
    }
        self.size = 0

    def find(self, x):
        root = x
        while self.father[root] is not None:
            root = self.father[root]

        return root

    def merge(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)

        if root_x != root_y:
            self.father[root_x] = self.father[root_y]
            self.size -= 1

    def add(self, x):
        if x not in self.father:
            self.father[x] = None
            self.size += 1


uf = UnionFind()
for i in range(1, 6):
    uf.add(i)

uf.merge(1, 2)
uf.merge(2, 3)
uf.merge(4, 5)

print(uf.size)

Supongo que te gusta

Origin blog.csdn.net/weixin_50791900/article/details/112756766
Recomendado
Clasificación