Skip to content
UPEEC

Dijkstra's Algorithm

Shortest paths from one source in a graph with non-negative edge weights.

Advanced
Comments 0

Dijkstra repeatedly takes the unvisited vertex with the smallest known distance (using a priority queue) and relaxes its edges:

d[v]=min⁡(d[v], d[u]+w(u,v))d[v] = \min(d[v],\ d[u] + w(u, v))

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 O((V+E)log⁡V)O((V + E)\log V). 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.