Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict as dd
- import heapq as hq
- class Solution:
- #Function to find the shortest distance of all the vertices
- #from the source vertex S.
- def dijkstra(self, v, g, s):
- adj=dd(list)
- for i in range(v):
- for j,w in g[i]:
- adj[i].append((j,w))
- vis=set()
- dis=[1e9]*v
- dis[s]=0
- vis=set()
- h=[(0,s)]
- while h:
- w1,n1=hq.heappop(h)
- if n1 in vis: continue
- vis.add(n1)
- for n2,w2 in adj[n1]:
- if n2 in vis:continue
- if dis[n2]>w1+w2:
- dis[n2]=w1+w2
- hq.heappush(h,(dis[n2],n2))
- return dis
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement