-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc-1319.py
53 lines (40 loc) · 1.35 KB
/
lc-1319.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
47
48
49
50
51
52
53
'''
LC-1319 - Number of Operations to Make Network Connected
Algo: Union Find
Type: Graph
Author: Rishabh IO
Language: Python3
Time Complexity: O(n)
Space Complexity: O(n)
Reference: https://www.youtube.com/watch?v=Kptz-NVA2RE
'''
class Solution:
def makeConnected(self, n: int, connections):
parents = [ i for i in range(n)]
def find(x):
if parents[x] != x:
parents[x] = find(parents[x])
return parents[x]
def union(a, b):
root_a = find(a)
root_b = find(b)
if root_a == root_b:
return True
parents[root_a] = root_b
return False
extra_edges = 0
for a, b in connections:
if union(a, b):
extra_edges += 1
components = 0
for i in range(n):
if i == find(i):
components += 1
if extra_edges >= components - 1:
return components - 1
else:
return -1
if __name__ == "__main__":
n = 4
connections = [[0,1],[0,2],[1,2]]
print(Solution().makeConnected(n, connections))