Skip to content

Instantly share code, notes, and snippets.

@nvictus
Last active July 5, 2023 03:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nvictus/7854213 to your computer and use it in GitHub Desktop.
Save nvictus/7854213 to your computer and use it in GitHub Desktop.
Python: Dijkstra's algorithm using the pqdict module
from pqdict import pqdict
def dijkstra(graph, source, target=None):
dist = {} # lengths of the shortest paths to each node
pred = {} # predecessor node in each shortest path
# Store distance scores in a priority queue dictionary
pq = pqdict.minpq()
for node in graph:
if node == source:
pq[node] = 0
else:
pq[node] = float('inf')
# popitems always pops out the node with min score
# Removing a node from pqdict is O(log n).
for node, min_dist in pq.popitems():
dist[node] = min_dist
if node == target:
break
for neighbor in graph[node]:
if neighbor in pq:
new_score = dist[node] + graph[node][neighbor]
if new_score < pq[neighbor]:
# Updating the score of a node is O(log n) using pqdict.
pq[neighbor] = new_score
pred[neighbor] = node
return dist, pred
def shortest_path(graph, source, target):
dist, pred = dijkstra(graph, source, target)
end = target
path = [end]
while end != source:
end = pred[end]
path.append(end)
path.reverse()
return path
if __name__=='__main__':
# A simple edge-labeled graph using a dict of dicts
graph = {'a': {'b':14, 'c':9, 'd':7},
'b': {'a':14, 'c':2, 'e':9},
'c': {'a':9, 'b':2, 'd':10, 'f':11},
'd': {'a':7, 'c':10, 'f':15},
'e': {'b':9, 'f':6},
'f': {'c':11, 'd':15, 'e':6}}
dist, pred = dijkstra(graph, source='a')
print(dist)
print(pred)
print(shortest_path(graph, 'a', 'e'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment