From c7474f33a4754c6bbfc60441369914b5b0109bdd Mon Sep 17 00:00:00 2001 From: Grzegorz Kucmierz Date: Wed, 18 Dec 2019 15:35:04 +0100 Subject: [PATCH] Dynamic Connectivity --- dynamic-connectivity/index.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 dynamic-connectivity/index.py diff --git a/dynamic-connectivity/index.py b/dynamic-connectivity/index.py new file mode 100644 index 0000000..c00fbab --- /dev/null +++ b/dynamic-connectivity/index.py @@ -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)