Dijkstra's Algorithm
Problem Link: https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1
import heapq
from collections import defaultdict
class Solution:
#Function to find the shortest distance of all the vertices
#from the source vertex S.
def dijkstra(self, v, l, source):
#code here
adj=defaultdict(list)
for i in range(len(l)):
for j in range(len(l[i])):
adjnode=l[i][j][0]
weight=l[i][j][1]
adj[i].append([adjnode,weight])
distance=[float('inf') for i in range(v)]
distance[source]=0
pq=[(source,0)]
heapq.heapify(pq)
while(len(pq)>0):
curr=heapq.heappop(pq)
node=curr[0]
dist=curr[1]
for i in adj[node]:
adjnode=i[0]
weight=i[1]
if(dist+weight<distance[adjnode]):
distance[adjnode]=dist+weight
heapq.heappush(pq,(adjnode,distance[adjnode]))
return distance
Last updated