Skip to content

Commit cadad75

Browse files
authored
Create 1584-Min-Cost-to-Connect-all-Points.py
1 parent 92bb311 commit cadad75

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def minCostConnectPoints(self, points: List[List[int]]) -> int:
3+
N = len(points)
4+
adj = { i:[] for i in range(N) } # i : list of [cost, node]
5+
for i in range(N):
6+
x1, y1 = points[i]
7+
for j in range(i + 1, N):
8+
x2, y2 = points[j]
9+
dist = abs(x1 - x2) + abs(y1 - y2)
10+
adj[i].append([dist, j])
11+
adj[j].append([dist, i])
12+
13+
# Prim's
14+
res = 0
15+
visit = set()
16+
minH = [[0, 0]] # [cost, point]
17+
while len(visit) < N:
18+
cost, i = heapq.heappop(minH)
19+
if i in visit:
20+
continue
21+
res += cost
22+
visit.add(i)
23+
for neiCost, nei in adj[i]:
24+
if nei not in visit:
25+
heapq.heappush(minH, [neiCost, nei])
26+
return res

0 commit comments

Comments
 (0)