-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path1584-min-cost-to-connect-all-points.py
49 lines (42 loc) · 1.39 KB
/
1584-min-cost-to-connect-all-points.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
class UnionFind:
def __init__(self, n):
self.parent = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
def find(self, p):
while p != self.parent[p]:
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def union(self, p, q):
root_p = self.find(p)
root_q = self.find(q)
if root_p == root_q:
return
if self.rank[root_p] > self.rank[root_q]:
self.parent[root_q] = root_p
elif self.rank[root_p] < self.rank[root_q]:
self.parent[root_p] = root_q
else:
self.parent[root_p] = root_q
self.rank[root_q] += 1
def is_connected(self, p, q):
return self.find(p) == self.find(q)
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
edges = []
for i in range(len(points)):
for j in range(i + 1, len(points)):
x1, y1 = points[i]
x2, y2 = points[j]
edges.append((abs(x1 - x2) + abs(y1 - y2), i, j))
edges.sort()
uf = UnionFind(len(points))
res = 0
for w, i, j in edges:
if not uf.is_connected(i, j):
uf.union(i, j)
res += w
return res
# time O(ElogE)
# space O(V + E)
# using graph and kruskal and mst and union find