forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Operations to Make Network Connected.py
46 lines (42 loc) · 1.31 KB
/
Number of Operations to Make Network Connected.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Runtime: 772 ms (Top 55.10%) | Memory: 34.3 MB (Top 72.08%)
class Solution(object):
def __init__(self):
self.parents = []
self.count = []
def makeConnected(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: int
"""
if len(connections) < n-1:
return -1
self.parents = [i for i in range(n)]
self.count = [1 for _ in range(n)]
for connection in connections:
a, b = connection[0], connection[1]
self.union(a, b)
return len({self.find(i) for i in range(n)}) - 1
def find(self, node):
"""
:type node: int
:rtype: int
"""
while(node != self.parents[node]):
node = self.parents[node];
return node
def union(self, a, b):
"""
:type a: int
:type b: int
:rtype: None
"""
a_parent, b_parent = self.find(a), self.find(b)
a_size, b_size = self.count[a_parent], self.count[b_parent]
if a_parent != b_parent:
if a_size < b_size:
self.parents[a_parent] = b_parent
self.count[b_parent] += a_size
else:
self.parents[b_parent] = a_parent
self.count[a_parent] += b_size