Advertisement
Iam_Sandeep

Dijkstra Algorithm

Jun 21st, 2022
1,041
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. from collections import defaultdict as dd
  2. import heapq as hq
  3. class Solution:
  4.  
  5.     #Function to find the shortest distance of all the vertices
  6.     #from the source vertex S.
  7.     def dijkstra(self, v, g, s):
  8.         adj=dd(list)
  9.         for i in range(v):
  10.             for j,w in g[i]:
  11.                 adj[i].append((j,w))
  12.        
  13.         vis=set()
  14.         dis=[1e9]*v
  15.         dis[s]=0
  16.         vis=set()
  17.         h=[(0,s)]
  18.         while h:
  19.             w1,n1=hq.heappop(h)
  20.             if n1 in vis: continue
  21.             vis.add(n1)
  22.             for n2,w2 in adj[n1]:
  23.                 if n2 in vis:continue
  24.                 if dis[n2]>w1+w2:
  25.                     dis[n2]=w1+w2
  26.                     hq.heappush(h,(dis[n2],n2))
  27.         return dis
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement