1135. Connecting Cities With Minimum Cost
class Solution:
def minimumCost(self, n: int, connections: List[List[int]]) -> int:
table = defaultdict(list)
for city1, city2, cost in connections:
table[city1].append((cost, city2))
table[city2].append((cost, city1))
heap = []
heapq.heappush(heap, (0, 1))
seen = set()
total = 0
while heap and len(seen) < n:
cost, city = heapq.heappop(heap)
if city not in seen:
seen.add(city)
total += cost
for neighbor_cost, neighbor in table[city]:
heapq.heappush(heap, (neighbor_cost, neighbor))
return total if len(seen) == n else -1Last updated