Last active
February 13, 2021 19:07
-
-
Save abecus/efe9f0fbd940dad1ad88489d80700796 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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