-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminCostConnectPoints.py
28 lines (24 loc) · 1 KB
/
minCostConnectPoints.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
# Prim algorithm
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
def manhattan(i, j):
x, y = points[i], points[j]
return abs(x[0] - y[0]) + abs(x[1] - y[1])
def cal_weight():
weight = [[0 for _ in range (N)] for _ in range (N)]
for i in range (N):
for j in range (i + 1, N):
weight[i][j] = manhattan(i, j)
weight[j][i] = weight[i][j]
return weight
N, output = len(points), 0
seen, heap, weight = set(), [(0, 0)], cal_weight()
while len(seen) < N:
dist, idx = heappop(heap)
if idx not in seen:
output += dist
seen.add(idx)
for nei_idx in range(N):
if nei_idx not in seen and nei_idx != idx:
heappush(heap, (weight[nei_idx][idx], nei_idx))
return output