Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created April 18, 2021 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amankharwal/18124f38ac73f27322226a1bf5cf0140 to your computer and use it in GitHub Desktop.
Save amankharwal/18124f38ac73f27322226a1bf5cf0140 to your computer and use it in GitHub Desktop.
from heapq import *
from collections import defaultdict
def dijkstra(edges, strat_node, end_node):
g = defaultdict(list)
for start, end, weight in edges:
g[start].append((weight, end))
q, visited = [(0, strat_node,())], set()
while q:
(cost,v1,path) = heappop(q)
if v1 not in visited:
visited.add(v1)
path = (v1, path)
if v1 == end_node:
return (cost, path)
for c, v2 in g.get(v1, ()):
if v2 not in visited:
heappush(q, (cost+c, v2, path))
print (q)
return float("inf")
if __name__ == "__main__":
edges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 7),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("F", "G", 11)
]
print ("=== Dijkstra ===")
print ("A >> G:")
print (dijkstra(edges, "A", "G"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment