Skip to content

Instantly share code, notes, and snippets.

@inoryy
Created January 25, 2017 18:48
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 inoryy/7fab0b6ef446e6bf7a81a04f793b2cfb to your computer and use it in GitHub Desktop.
Save inoryy/7fab0b6ef446e6bf7a81a04f793b2cfb to your computer and use it in GitHub Desktop.
from heapq import heappop, heappush
def dijkstra(g, s, f):
h = [(0,s)]
cost, prev = {}, {}
cost[s], prev[s] = 0, None
while len(h) > 0:
_,v = heappop(h)
if v == f:
break
for adj, adj_cost in g[v]:
new_cost = cost[v] + adj_cost
if new_cost < cost.get(adj, float('inf')):
cost[adj], prev[adj] = new_cost, v
heappush(h, (new_cost, adj))
curr, path = f, [f]
while curr in prev and prev[curr] != None:
curr = prev[curr]
path.append(curr)
return path[::-1], cost.get(f, float('inf'))
if __name__ == '__main__':
g = {'s':[('v',1),('w',4)],'v':[('w',2),('t',6)],'w':[('t',3)],'t':[]}
print(dijkstra(g, 's', 't') == (['s', 'v', 'w', 't'], 6))
print(dijkstra(g, 's', 'e') == (['e'], float('inf')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment