Skip to content

Instantly share code, notes, and snippets.

@abecus
Last active February 13, 2021 19:07
Show Gist options
  • Save abecus/efe9f0fbd940dad1ad88489d80700796 to your computer and use it in GitHub Desktop.
Save abecus/efe9f0fbd940dad1ad88489d80700796 to your computer and use it in GitHub Desktop.
from collections import defaultdict
import heapq as heap
def dijkstra(G, startingNode):
visited = set()
parentsMap = {}
pq = []
nodeCosts = defaultdict(lambda: float('inf'))
nodeCosts[startingNode] = 0
heap.heappush(pq, (0, startingNode))
while pq:
# go greedily by always extending the shorter cost nodes first
_, node = heap.heappop(pq)
visited.add(node)
for adjNode, weight in G[node].items():
if adjNode in visited: continue
newCost = nodeCosts[node] + weight
if nodeCosts[adjNode] > newCost:
parentsMap[adjNode] = node
nodeCosts[adjNode] = newCost
heap.heappush(pq, (newCost, adjNode))
return parentsMap, nodeCosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment