Dijkstra's Algorithm
Shortest paths from one source in a graph with non-negative edge weights.
Advanced
Dijkstra repeatedly takes the unvisited vertex with the smallest known distance (using a priority queue) and relaxes its edges:
import heapq
def dijkstra(graph, src):
dist = {src: 0}
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float("inf")):
continue
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return dist
Complexity . It fails with negative weights — use Bellman-Ford for those.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.