Shortest Path Problem
Find the shortest path from
Theory
Greedily go to the next-closest vertex
Implementation
from heapq import heappush, heappop
def dijkstra(s, adj):
dist = [float('inf') for _ in range(len(adj)]
dist[s] = 0
pq = [(0, s)]
while len(pq) > 0:
d, c = heappop(pq)
for n, w in adj[c]:
if dist[c] + w < dist[n]:
dist[n] = dist[c] + w
heappush(pq, (dist[n], n))
return dist
Runtime
Priority queue takes