Dynamic Connectivity

This commit is contained in:
2019-12-18 15:35:04 +01:00
parent 6e0cdece47
commit c7474f33a4

View File

@@ -0,0 +1,17 @@
# https://www.codewars.com/kata/dynamic-connectivity/python
class DynamicConnectivity(object):
def __init__(self, n):
self.__map = list(range(0, n))
def __root(self, p):
while p != self.__map[p]:
self.__map[p] = self.__map[self.__map[p]]
p = self.__map[p]
return p
def union(self, p, q):
self.__map[self.__root(p)] = self.__root(q)
def connected(self, p, q):
return self.__root(p) == self.__root(q)