graph = {
0:[(1,24),(3,20),(2,3)],
1:[(0,24)],
2:[(0,3),(3,12)],
3:[(2,12),(0,20)]
}
from collections import defaultdict
from heapq import *
def dj(graph,source):
dist = defaultdict(int)
heap = [(0,source)]
new_dist={}
dist[source] = 0
for i in range(1,4):
heappush(heap,(10000,i))
dist[i]=10000
visited = set()
while len(heap):
c_dist,c_vertex = heappop(heap)
if c_vertex not in visited:
visited.add(c_vertex)
for nbr,cost in graph[c_vertex]:
if c_dist+cost < dist[nbr]:
dist[nbr] = c_dist+cost
new_dist[c_vertex] = dist[c_vertex]
while len(heap):
heappop(heap)
dist.pop(c_vertex)
heap = [(disti,vertex) for vertex, disti in dist.items()]
heapify(heap)
print new_dist
dj(graph,0)