Algorithm · Graphs · O((V + E) log V)

Dijkstra’s shortest paths

Single-source shortest paths with non-negative edge weights: settle the closest unsettled vertex, relax its edges, repeat. O((V + E) log V) with a binary heap.

The full derivation, edge cases and exercises are in the lesson Dijkstra’s algorithm with a binary heap. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Dijkstra’s algorithm is BFS with a priority queue: instead of edge count it orders vertices by tentative distance. When the closest vertex is popped, no shorter path to it can exist because every other path would have to pass through a vertex at least as far away and then add a non-negative weight.

The lab uses lazy deletion: a shorter distance pushes a new heap entry, and stale entries are skipped when they are popped.

Steps

  1. dist[source] = 0, every other distance ∞; push the source.
  2. Pop the entry with the smallest distance; skip it if stale.
  3. Relax each outgoing edge: if dist[u] + w < dist[v], update dist[v], record u as the predecessor and push v.
  4. Repeat until the heap is empty; follow predecessors to rebuild paths.

Invariants

What holds at every step; the correctness argument rests on these.

  • A popped, non-stale vertex has its final shortest distance.
  • dist[v] is always the length of some real path, or ∞.

Complexity

Dijkstra’s shortest paths complexity
CaseTimeExtra spaceNotes
Binary heap, lazy deletionO((V + E) log V)O(V + E)Requires all edge weights ≥ 0.

When to use it

Use it when

  • Road networks, routing, any weighted graph with non-negative weights.

Avoid it when

  • Negative edge weights: use Bellman–Ford.
  • All weights are equal: plain BFS is simpler and O(V + E).

Step through it

The interactive lab for dijkstra’s shortest paths: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Dijkstra in four languages, each checked against one shared fixture (distances, settle order with the (distance, node) tie-break, stale entries skipped and the reconstructed path, including unreachable nodes and zero weights) and 500 random graphs compared with Bellman-Ford.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>A directed edge u → v with a weight; an undirected graph lists each edge once and passes directed: false.</summary>
public readonly record struct WeightedEdge(int From, int To, int Weight);
 
/// <summary>Distances (Dijkstra.Unreachable for ∞), predecessors (-1 for none), settle order and stale heap entries skipped.</summary>
public sealed record ShortestPaths(int[] Distances, int[] Previous, List<int> SettleOrder, int StaleSkips);
 
/// <summary>
/// Dijkstra's single-source shortest paths with a binary heap and lazy deletion:
/// an improved distance enqueues a new entry, and entries that went stale are
/// skipped when dequeued. Priorities are (distance, node), so ties settle the
/// smaller node first. Requires non-negative weights. O((V + E) log V).
/// </summary>
public static class Dijkstra
{
    public const int Unreachable = int.MaxValue;
 
    public static ShortestPaths Run(int nodeCount, IReadOnlyList<WeightedEdge> edges, bool directed, int source)
    {
        var adjacency = new List<(int To, int Weight)>[nodeCount];
        for (int i = 0; i < nodeCount; i++)
            adjacency[i] = [];
        foreach (var e in edges)
        {
            if (e.Weight < 0)
                throw new ArgumentException($"Edge {e.From} -> {e.To} has negative weight {e.Weight}; Dijkstra needs weights >= 0.", nameof(edges));
            adjacency[e.From].Add((e.To, e.Weight));
            if (!directed)
                adjacency[e.To].Add((e.From, e.Weight));
        }
 
        var dist = new int[nodeCount];
        var prev = new int[nodeCount];
        Array.Fill(dist, Unreachable);
        Array.Fill(prev, -1);
        dist[source] = 0;
        var heap = new PriorityQueue<int, (int Dist, int Node)>(); // tuples compare by Dist, then Node
        heap.Enqueue(source, (0, source));
        var settleOrder = new List<int>();
        int staleSkips = 0;
 
        while (heap.TryDequeue(out int u, out var entry))
        {
            if (entry.Dist > dist[u]) // stale: a shorter path to u was found after this entry was pushed
            {
                staleSkips++;
                continue;
            }
            settleOrder.Add(u); // dist[u] is final
            foreach (var (v, weight) in adjacency[u])
            {
                int through = dist[u] + weight;
                if (through < dist[v])
                {
                    dist[v] = through;
                    prev[v] = u;
                    heap.Enqueue(v, (through, v));
                }
            }
        }
        return new ShortestPaths(dist, prev, settleOrder, staleSkips);
    }
 
    /// <summary>Nodes from the source to <paramref name="target"/>, or an empty list when it is unreachable.</summary>
    public static List<int> PathTo(ShortestPaths paths, int target)
    {
        var path = new List<int>();
        if (paths.Distances[target] == Unreachable)
            return path;
        for (int v = target; v != -1; v = paths.Previous[v])
            path.Add(v);
        path.Reverse();
        return path;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/Dijkstra.cs

"""Dijkstra's single-source shortest paths with a binary heap (heapq) and lazy deletion.
 
An improved distance pushes a new (distance, node) entry instead of decreasing a key;
entries that went stale are skipped when popped. Tuples compare by distance, then node,
so ties settle the smaller node first. Requires non-negative weights. O((V + E) log V).
"""
 
import heapq
import math
from dataclasses import dataclass
 
UNREACHABLE = math.inf
 
 
@dataclass
class ShortestPaths:
    dist: list[float]  # UNREACHABLE (math.inf) for nodes the source cannot reach
    prev: list[int | None]
    settle_order: list[int]
    stale_skips: int
 
 
def dijkstra(node_count: int, edges: list[tuple[int, int, int]], directed: bool, source: int) -> ShortestPaths:
    adjacency: list[list[tuple[int, int]]] = [[] for _ in range(node_count)]
    for u, v, weight in edges:
        if weight < 0:
            raise ValueError(f"edge {u} -> {v} has negative weight {weight}; Dijkstra needs weights >= 0")
        adjacency[u].append((v, weight))
        if not directed:
            adjacency[v].append((u, weight))
 
    dist: list[float] = [UNREACHABLE] * node_count
    prev: list[int | None] = [None] * node_count
    dist[source] = 0
    heap: list[tuple[float, int]] = [(0, source)]
    settle_order: list[int] = []
    stale_skips = 0
 
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:  # stale: a shorter path to u was found after this entry was pushed
            stale_skips += 1
            continue
        settle_order.append(u)  # dist[u] is final
        for v, weight in adjacency[u]:
            through = d + weight
            if through < dist[v]:
                dist[v] = through
                prev[v] = u
                heapq.heappush(heap, (through, v))
    return ShortestPaths(dist, prev, settle_order, stale_skips)
 
 
def path_to(paths: ShortestPaths, target: int) -> list[int]:
    """Nodes from the source to target, or [] when target is unreachable."""
    if paths.dist[target] == UNREACHABLE:
        return []
    path: list[int] = []
    node: int | None = target
    while node is not None:
        path.append(node)
        node = paths.prev[node]
    path.reverse()
    return path

Tested on CPython 3.14.0 · examples/python/dsa_examples/dijkstra.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
 
/**
 * Dijkstra's single-source shortest paths with a binary heap (PriorityQueue) and lazy
 * deletion: an improved distance offers a new entry, and entries that went stale are
 * skipped when polled. Entries compare by distance, then node, so ties settle the smaller
 * node first. Requires non-negative weights. O((V + E) log V).
 */
public final class Dijkstra {
    public static final int UNREACHABLE = Integer.MAX_VALUE;
 
    private Dijkstra() {
    }
 
    /** A directed edge; an undirected graph lists each edge once and passes directed = false. */
    public record Edge(int from, int to, int weight) {
    }
 
    /** dist is UNREACHABLE for nodes the source cannot reach; prev is -1 where there is no predecessor. */
    public record Result(int[] dist, int[] prev, List<Integer> settleOrder, int staleSkips) {
    }
 
    private record Entry(int dist, int node) {
    }
 
    private record Arc(int to, int weight) {
    }
 
    public static Result run(int nodeCount, List<Edge> edges, boolean directed, int source) {
        List<List<Arc>> adjacency = new ArrayList<>(nodeCount);
        for (int i = 0; i < nodeCount; i++) {
            adjacency.add(new ArrayList<>());
        }
        for (Edge e : edges) {
            if (e.weight() < 0) {
                throw new IllegalArgumentException("Edge " + e.from() + " -> " + e.to() + " has negative weight " + e.weight() + "; Dijkstra needs weights >= 0.");
            }
            adjacency.get(e.from()).add(new Arc(e.to(), e.weight()));
            if (!directed) {
                adjacency.get(e.to()).add(new Arc(e.from(), e.weight()));
            }
        }
 
        int[] dist = new int[nodeCount];
        int[] prev = new int[nodeCount];
        Arrays.fill(dist, UNREACHABLE);
        Arrays.fill(prev, -1);
        dist[source] = 0;
        PriorityQueue<Entry> heap = new PriorityQueue<>(Comparator.comparingInt(Entry::dist).thenComparingInt(Entry::node));
        heap.add(new Entry(0, source));
        List<Integer> settleOrder = new ArrayList<>();
        int staleSkips = 0;
 
        while (!heap.isEmpty()) {
            Entry entry = heap.poll();
            int u = entry.node();
            if (entry.dist() > dist[u]) { // stale: a shorter path to u was found after this entry was added
                staleSkips++;
                continue;
            }
            settleOrder.add(u); // dist[u] is final
            for (Arc arc : adjacency.get(u)) {
                int through = dist[u] + arc.weight();
                if (through < dist[arc.to()]) {
                    dist[arc.to()] = through;
                    prev[arc.to()] = u;
                    heap.add(new Entry(through, arc.to()));
                }
            }
        }
        return new Result(dist, prev, settleOrder, staleSkips);
    }
 
    /** Nodes from the source to target, or an empty list when target is unreachable. */
    public static List<Integer> pathTo(Result result, int target) {
        List<Integer> path = new ArrayList<>();
        if (result.dist()[target] == UNREACHABLE) {
            return path;
        }
        for (int v = target; v != -1; v = result.prev()[v]) {
            path.add(v);
        }
        Collections.reverse(path);
        return path;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/Dijkstra.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <functional>
#include <limits>
#include <queue>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A directed edge; an undirected graph lists each edge once and passes directed = false.
struct WeightedEdge {
    int from;
    int to;
    int weight;
};
 
inline constexpr int kUnreachable = std::numeric_limits<int>::max();
 
// dist is kUnreachable for nodes the source cannot reach; prev is -1 where there is no predecessor.
struct ShortestPaths {
    std::vector<int> dist;
    std::vector<int> prev;
    std::vector<int> settle_order;
    int stale_skips = 0;
};
 
// Dijkstra's single-source shortest paths with a binary heap (std::priority_queue) and
// lazy deletion: an improved distance pushes a new entry, and entries that went stale are
// skipped when popped. Pairs compare by distance, then node, so ties settle the smaller
// node first. Requires non-negative weights. O((V + E) log V).
inline ShortestPaths dijkstra(int node_count, const std::vector<WeightedEdge>& edges, bool directed, int source) {
    const auto n = static_cast<std::size_t>(node_count);
    std::vector<std::vector<std::pair<int, int>>> adjacency(n);  // (to, weight)
    for (const auto& e : edges) {
        if (e.weight < 0)
            throw std::invalid_argument("edge " + std::to_string(e.from) + " -> " + std::to_string(e.to) + " has a negative weight; Dijkstra needs weights >= 0");
        adjacency[static_cast<std::size_t>(e.from)].emplace_back(e.to, e.weight);
        if (!directed) adjacency[static_cast<std::size_t>(e.to)].emplace_back(e.from, e.weight);
    }
 
    using Entry = std::pair<int, int>;  // (distance, node)
    ShortestPaths r{std::vector<int>(n, kUnreachable), std::vector<int>(n, -1), {}, 0};
    r.dist[static_cast<std::size_t>(source)] = 0;
    std::priority_queue<Entry, std::vector<Entry>, std::greater<>> heap;  // min-heap
    heap.emplace(0, source);
 
    while (!heap.empty()) {
        const auto [d, u] = heap.top();
        heap.pop();
        const auto uu = static_cast<std::size_t>(u);
        if (d > r.dist[uu]) {  // stale: a shorter path to u was found after this entry was pushed
            ++r.stale_skips;
            continue;
        }
        r.settle_order.push_back(u);  // dist[u] is final
        for (const auto& [v, weight] : adjacency[uu]) {
            const auto vv = static_cast<std::size_t>(v);
            const int through = d + weight;
            if (through < r.dist[vv]) {
                r.dist[vv] = through;
                r.prev[vv] = u;
                heap.emplace(through, v);
            }
        }
    }
    return r;
}
 
// Nodes from the source to target, or an empty vector when target is unreachable.
inline std::vector<int> path_to(const ShortestPaths& paths, int target) {
    std::vector<int> path;
    if (paths.dist[static_cast<std::size_t>(target)] == kUnreachable) return path;
    for (int v = target; v != -1; v = paths.prev[static_cast<std::size_t>(v)]) path.push_back(v);
    std::ranges::reverse(path);
    return path;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/dijkstra.hpp

Learn more

Lessons

Data structures it uses

Problems, patterns and exercises

References