Skip to content

Commit 007113e

Browse files
committed
improved Min Cost to Repair Edges with Priority Queue
1 parent 4265ff0 commit 007113e

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

Graph/MinCostToRepairEdges/solution.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,36 @@
11
from collections import defaultdict
2+
import queue
23

34

4-
def updateCost(neighbors, b, cost):
5-
for i in range(len(neighbors)):
6-
if neighbors[i][0] == b:
7-
neighbors[i][1] = cost
5+
def updateCost(arr, key, val):
6+
return [(k, v) if v != val else (key, val) for (k, v) in arr]
87

98

109
def minCostRepair(n, edges, edgesToRepair):
1110
# create edge lists associated with cost
1211
edgeList = defaultdict(list)
1312
for a, b in edges:
14-
edgeList[a].append([b, 0])
15-
edgeList[b].append([a, 0])
16-
# print(edgeList)
13+
edgeList[a].append((0, b))
14+
edgeList[b].append((0, a))
15+
print(edgeList)
1716
for a, b, cost in edgesToRepair:
18-
updateCost(edgeList[a], b, cost)
19-
updateCost(edgeList[b], a, cost)
20-
# print(edgeList)
17+
edgeList[a] = updateCost(edgeList[a], cost, b)
18+
edgeList[b] = updateCost(edgeList[b], cost, a)
19+
print(edgeList)
2120
# find shorted spanning graph
2221
reached = set()
2322
totalCost = 0
24-
queue = list()
25-
queue.append([1, 0])
23+
pq = queue.PriorityQueue()
24+
pq.put((0, 1))
2625
while len(reached) < n:
27-
current = queue.pop(0)
28-
currentNode = current[0]
29-
cost = current[1]
26+
current = pq.get()
27+
currentNode = current[1]
28+
cost = current[0]
3029
if currentNode not in reached:
3130
reached.add(currentNode)
3231
totalCost += cost
33-
queue.extend(edgeList[currentNode])
34-
queue.sort(key=lambda pair: pair[1])
32+
for neighbor in edgeList[currentNode]:
33+
pq.put(neighbor)
3534
return totalCost
3635

3736

0 commit comments

Comments
 (0)