TExcelTAD
Home › Graph Algorithms › Dijkstra's Algorithm

Dijkstra's Algorithm

When every edge weight is non-negative, there is a much faster way to get single-source shortest paths than Bellman-Ford. Dijkstra's algorithm (1959) grows a set SS of vertices whose distances are final, like a breadth-first search that measures distance in weight instead of in edges. At every step it picks the vertex outside SS with the smallest estimate, declares that estimate final, and relaxes the edges leaving it. Every edge is relaxed exactly once, as in the DAG algorithm, but the order comes from a priority queue instead of a topological sort. Route planners, network routing protocols such as OSPF and IS-IS, and countless game engines use it. The DSA course has a first look; this lesson states it precisely, and the next two prove it correct and analyse its running time.

The algorithm

text
DIJKSTRA(G, w, s)                       // requires w(u, v) >= 0 for every edge
1  INITIALIZE-SINGLE-SOURCE(G, s)
2  S = empty set
3  Q = a min-priority queue of all vertices, keyed by their d values
4  while Q is not empty
5      u = EXTRACT-MIN(Q)               // the closest vertex not yet final
6      S = S + {u}
7      for each v in G.Adj[u]
8          RELAX(u, v, w)               // a decrease of v.d is a DECREASE-KEY in Q

It looks almost exactly like Prim's algorithm. The only difference is the key: Prim keys a vertex by the weight of the single edge connecting it to the tree, Dijkstra by the length of the whole path from ss.

Watching it work

The graph is a small road network; weights are travel times in minutes. Labels show the current estimates.

The Python version uses heapq with lazy deletion: when an estimate decreases it pushes a new entry, and entries for vertices already in SS are skipped when popped. Entries are (distance, name) pairs, so ties are broken by name, as in the animation. It prints the same steps.

python · try it yourself
import heapq

edges = [("A", "B", 4), ("A", "C", 2), ("B", "C", 1), ("B", "D", 5), ("C", "D", 8), ("C", "E", 10),
         ("D", "E", 2), ("D", "F", 6), ("E", "F", 2), ("E", "G", 7), ("F", "G", 3)]
adj = {v: [] for v in "ABCDEFG"}
for u, v, w in edges:
    adj[u].append((v, w)); adj[v].append((u, w))
for v in adj:
    adj[v].sort()

def dijkstra(adj, s):
    INF = float("inf")
    d = {v: INF for v in adj}
    pi = {v: None for v in adj}
    d[s] = 0
    done = set()
    pq = [(0, s)]
    while pq:
        du, u = heapq.heappop(pq)
        if u in done:
            continue                                  # stale entry
        done.add(u)
        print(f"settle {u} at distance {du}")
        for v, w in adj[u]:
            if v in done:
                continue
            if du + w < d[v]:
                print(f"  relax {u}->{v}: {du} + {w} = {du + w} < {d[v]}, update")
                d[v], pi[v] = du + w, u
                heapq.heappush(pq, (d[v], v))
            else:
                print(f"  {u}->{v}: {du} + {w} = {du + w} is not better than {d[v]}")
    return d, pi

d, pi = dijkstra(adj, "A")
print("distances:", d)

def path(v):
    return path(pi[v]) + [v] if pi[v] else [v]
print("route to G:", " -> ".join(path("G")), f"({d['G']} minutes)")
settle A at distance 0
  relax A->B: 0 + 4 = 4 < inf, update
  relax A->C: 0 + 2 = 2 < inf, update
settle C at distance 2
  relax C->B: 2 + 1 = 3 < 4, update
  relax C->D: 2 + 8 = 10 < inf, update
  relax C->E: 2 + 10 = 12 < inf, update
settle B at distance 3
  relax B->D: 3 + 5 = 8 < 10, update
settle D at distance 8
  relax D->E: 8 + 2 = 10 < 12, update
  relax D->F: 8 + 6 = 14 < inf, update
settle E at distance 10
  relax E->F: 10 + 2 = 12 < 14, update
  relax E->G: 10 + 7 = 17 < inf, update
settle F at distance 12
  relax F->G: 12 + 3 = 15 < 17, update
settle G at distance 15
distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 12, 'G': 15}
route to G: A -> C -> B -> D -> E -> F -> G (15 minutes)

The vertices are settled in the order A,C,B,D,E,F,GA, C, B, D, E, F, G, which is also the order of their final distances 0,2,3,8,10,12,150, 2, 3, 8, 10, 12, 15. That is no accident: Dijkstra's algorithm settles vertices in non-decreasing order of distance, the fact at the heart of its correctness proof. Notice also BB: its first estimate 4 (directly from AA) is improved to 3 by the detour through CC, before BB is settled.

In C++

The standard C++ version uses std::priority_queue with std::greater, which turns it into a min-heap, and the same lazy deletion.

cpp · try it yourself
#include <climits>
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>

int main() {
    const int n = 7;                                                   // A..G
    struct E { char u, v; int w; };
    std::vector<E> edges = {{'A','B',4}, {'A','C',2}, {'B','C',1}, {'B','D',5}, {'C','D',8}, {'C','E',10},
                            {'D','E',2}, {'D','F',6}, {'E','F',2}, {'E','G',7}, {'F','G',3}};
    std::vector<std::vector<std::pair<int, int>>> adj(n);
    for (auto e : edges) {
        adj[e.u - 'A'].push_back({e.v - 'A', e.w});
        adj[e.v - 'A'].push_back({e.u - 'A', e.w});
    }
    std::vector<long long> d(n, LLONG_MAX);
    std::vector<int> pi(n, -1);
    using Item = std::pair<long long, int>;                            // (distance, vertex)
    std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
    d[0] = 0;
    pq.push({0, 0});
    while (!pq.empty()) {
        auto [du, u] = pq.top();
        pq.pop();
        if (du > d[u]) continue;                                       // stale entry
        for (auto [v, w] : adj[u])
            if (du + w < d[v]) { d[v] = du + w; pi[v] = u; pq.push({d[v], v}); }
    }
    for (int v = 0; v < n; ++v)
        std::printf("%c: %lld via %c\n", 'A' + v, d[v], pi[v] < 0 ? '-' : 'A' + pi[v]);
}
A: 0 via -
B: 3 via C
C: 2 via A
D: 8 via B
E: 10 via D
F: 12 via E
G: 15 via F

The test du > d[u] is the usual C++ way to detect a stale entry without a separate "done" set: an entry is stale exactly when a smaller distance for the same vertex was recorded after it was pushed.

Why negative weights break it

Dijkstra declares a vertex final the moment it is extracted. With non-negative weights no later path can be shorter, since any path that leaves SS only gets longer. A negative edge invalidates that reasoning. In the graph below, BB is settled at distance 2, but the path A→C→BA \to C \to B costs 5−4=15 - 4 = 1.

python · try it yourself
import heapq

def dijkstra(adj, s):
    d, done, pq = {v: float("inf") for v in adj}, set(), [(0, s)]
    d[s] = 0
    while pq:
        du, u = heapq.heappop(pq)
        if u in done:
            continue
        done.add(u)
        for v, w in adj[u]:
            if v not in done and du + w < d[v]:
                d[v] = du + w
                heapq.heappush(pq, (d[v], v))
    return d

def bellman_ford(adj, s):
    d = {v: float("inf") for v in adj}
    d[s] = 0
    for _ in range(len(adj) - 1):
        for u in adj:
            for v, w in adj[u]:
                d[v] = min(d[v], d[u] + w)
    return d

adj = {"A": [("B", 2), ("C", 5)], "B": [("D", 1)], "C": [("B", -4)], "D": []}
print("Dijkstra:    ", dijkstra(adj, "A"))
print("Bellman-Ford:", bellman_ford(adj, "A"))
Dijkstra:     {'A': 0, 'B': 2, 'C': 5, 'D': 3}
Bellman-Ford: {'A': 0, 'B': 1, 'C': 5, 'D': 2}

Dijkstra settles BB at 2 and DD at 3, and when CC later offers BB a value of 1, BB is already final and the improvement is never propagated to DD. Bellman-Ford gets B=1B = 1 and D=2D = 2. Adding a constant to every weight to make them non-negative does not fix this either: it penalizes paths with many edges. The correct reweighting, which preserves shortest paths, is Johnson's.

Running time in brief

Each vertex is extracted once and each edge relaxed once. With a binary heap, VV extractions and up to EE decrease-keys (or pushes, with lazy deletion) cost O(lg⁡V)O(\lg V) each, for O((V+E)lg⁡V)O((V + E) \lg V), which is O(Elg⁡V)O(E \lg V) when every vertex is reachable. Dijkstra with Different Priority Queues compares this with an array (O(V2)O(V^2)) and a Fibonacci heap (O(E+Vlg⁡V)O(E + V \lg V)). Practise with Shortest Distances.

Test yourself

What is the essential difference between Dijkstra's and Prim's algorithms?

  1. Dijkstra uses a stack
  2. Dijkstra keys a vertex by the length of the whole path from the source, Prim by the weight of one connecting edge
  3. Prim allows negative weights
  4. There is none

In which order does Dijkstra's algorithm settle vertices?

  1. Alphabetical
  2. In non-decreasing order of their final distance from ss
  3. In BFS order
  4. In order of degree

Why does adding a constant to every weight not make Dijkstra correct on graphs with negative edges?

  1. It makes weights fractional
  2. It changes which path is shortest, because a path with kk edges gains kk times the constant
  3. It creates negative cycles
  4. It does make it correct