用prim算法暴力求解,可以出来但是超时了
cost = 0
clique = [0]
while len(clique)<len(points):
distance = float('inf')
toadd = 0
for i in range(1,len(points)):
if i in clique:
continue
for j in clique:
temp_dis = abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1])
if temp_dis < distance:
toadd = i
distance = temp_dis
cost += distance
clique.append(toadd)
return cost
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
manhattan = lambda p1, p2: abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
n, c = len(points), collections.defaultdict(list)
for i in range(n):
for j in range(i+1, n):
d = manhattan(points[i], points[j])
c[i].append((d, j))
c[j].append((d, i))
cnt, ans, visited, heap = 1, 0, [0] * n, c[0]
visited[0] = 1
heapq.heapify(heap)
while heap:
d, j = heapq.heappop(heap)
if not visited[j]:
visited[j], cnt, ans = 1, cnt+1, ans+d
for record in c[j]: heapq.heappush(heap, record)
if cnt >= n: break
return ans