Прошло много времени, но я думаю, что смысл кучи в том, чтобы сохранить очередь узлов минимального расстояния для пересчета и обновления ваших расстояний.
import heapq
def dijkstra(graph, src):
# Read all graph nodes
nodes = list(graph.keys())
# Initialize all distances to infinity and build a queue of unvisted nodes
dist = {}
pq = []
for node in nodes:
dist[node] = float('inf')
dist[src] = 0
heapq.heappush(pq, (0, src))
# While shorter distances to nodes, recalculate neighbor distances
while pq:
src_dist, unvisited_node = heapq.heappop(pq)
# Recalculate total distance for each neighbor
unvisted_neighbors = graph.get(unvisited_node, [])
for n_node, n_dist in unvisted_neighbors:
test_dist = src_dist + n_dist
# If test distance is shorted, update and enqueue
if test_dist < dist[n_node]:
dist[n_node] = test_dist
heapq.heappush(pq, (test_dist, n_node))
return dist
test_graph = {
'a': (('b', 7), ('c', 9), ('f', 14)),
'b': (('a', 7), ('d', 15), ('c', 10)),
'c': (('a', 9), ('b', 10), ('d', 11), ('f', 2)),
'd': (('b', 15), ('c', 11), ('e', 6)),
'e': (('d', 6), ('f', 9)),
'f': (('c', 2), ('e', 9))
}
'''Lazy graph structure.
key: source node name
value: adjacent node name and distance pairs
https://www.bogotobogo.com/python/images/Graph/graph_diagram.png
'''
src_node = 'e'
d = dijkstra(test_graph, src_node)
for k, v in d.items():
print(f'{src_node}->{k}: {v}')