algosgraphs

dijkstra

shortest paths over weighted edges: settle the closest vertex next, and never look back.

report a mistake
.md

from one source, settle the closest vertex that isn't settled yet, then relax its edges, so a neighbor that gets closer takes the new distance and goes in the heap. a settled vertex never gets closer, since every path still open starts at least as far out and weights only add.

time
O((n + m) log n) a push and a pop per relax that lowers a dist, each log n deep
space
O(n + m) dist, parent and done per vertex, and a heap of at most m + 1 entries
needs
weights ≥ 0 one negative edge, and a settled vertex can get closer after all
without a heap
O(n²) scan every vertex for the closest one, n times. fine when m is near n²
reach for it
  • routes on a map, with distances or times on the edges
  • the shortest-path tree a router builds for ospf
  • the cheapest way through anything with a cost per step, flights, hops, effort
  • a*, which is this plus a guess of what's left
  • unweighted graphs don't need it, bfs is simpler and faster there
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the relax and the settle, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

dijkstra’s algorithm finds the shortest path from one vertex to every other, when the edges have weights. bfs counts edges. here an edge costs what its weight says, and the cheapest path may take more edges than the direct one. the idea is greedy: of the vertices found but not settled, settle the closest, then relax its edges, which may bring its neighbors closer. a settled vertex never gets closer, as long as no weight is negative. a heap hands out the closest vertex, and that’s the whole algorithm. e. w. dijkstra published it in 1959, in a three-page note.1 ospf, a routing protocol, builds each router’s tree of shortest paths with it.2

the idea

six vertices and nine edges, each with a weight. from 0, every other vertex is ∞: not found yet. the heap holds one entry, (0, 0): a distance, then a vertex.

an animation in six steps on a graph of 6 vertices, 0 to 5, and 9 edges with their weights written on them: 0 to 1 costs 4, 0 to 2 costs 1, 1 to 2 costs 2, 1 to 3 costs 5, 2 to 3 costs 8, 1 to 4 costs 6, 3 to 4 costs 3, 3 to 5 costs 2 and 4 to 5 costs 1. each vertex carries its distance from 0, ∞ until it's found, and a strip shows the heap's entries as (distance, vertex), smallest first, with the entry just popped on a row above them. a found vertex has a dashed ring, a settled one is filled white, and the edge to each vertex's parent is cyan. 0 settles first and finds 1 at 4 and 2 at 1. 2 settles at 1 and brings 1 down to 3, so 1's cyan edge moves from 0 to 2, and the old entry (4, 1) fades in the strip: stale. 3 is found at 9. 1 settles at 3, brings 3 down to 8 and finds 4 at 9, then the stale (4, 1) comes out and is skipped. 3 settles at 8: its edge to 4 gives 11, more than 9, and 5 is found at 10. (9, 3) comes out stale, 4 settles at 9, and its edge to 5 gives 10, a tie, so 5 keeps its parent 3. 5 settles at 10 with the heap empty, and the path to it lights up white along the cyan tree: 0, 2, 1, 3, 5. counters read 8 pops, 2 of them stale, and 8 pushes.

watch it run

step through the run on the page’s graph, or on a random one, from any vertex. the vertex just popped has a white ring, settled vertices are filled, found ones have a dashed ring, the edge being looked at is white, and each vertex’s edge to its parent is cyan. the heap reads in the order its entries come out, smallest first, and an entry whose vertex has a shorter dist already is faded: it’s stale. the pseudocode follows along.

weights on the edges
4125863210123450∞∞∞∞∞
poppedheap-(0, 0)top

dist[0] = 0, and (0, 0) goes in the heap. nothing else is found yet

pops
0
stale
0
pushes
1
looks
0
step
1 of 43
pseudocode
dijkstra(adj, src):  # adj[u] holds (v, w) for each edge u → v, w >= 0  dist = [-1] * n; parent = [-1] * n; done = [false] * n  dist[src] = 0; heap = [(0, src)]  # (dist, vertex) entries, smallest first  while heap:    d, u = pop(heap)  # the closest vertex not settled yet    if done[u]: continue  # stale: u settled with a smaller dist already    done[u] = true  # dist[u] is final    for v, w in adj[u]:      if done[v]: continue      if dist[v] == -1 or d + w < dist[v]:  # found, or found a shorter way        dist[v] = d + w; parent[v] = u        push(heap, (dist[v], v))  # an older entry for v goes stale  return dist, parent path_to(found, v):  if found.dist[v] == -1: return []  path = []  while v != -1: path.append(v); v = found.parent[v]  return reversed(path)

an interactive stepper on the page's graph of 6 vertices, or a random one of 6 to 8 on a circle, with every vertex's distance so far next to it, ∞ before it's found, the heap's entries as (distance, vertex), smallest first, the entry just popped above them, and the pseudocode under it all. each step pops the smallest entry, skips it when its vertex is done, settles the vertex, or looks along one edge and says whether the neighbor is found, brought closer, tied, left as it is, or done already. the vertex just popped has a white ring, settled vertices are filled, found ones have a dashed ring, the edge being looked at is white, each vertex's edge to its parent is cyan, and stale entries are faded. counters give the pops, the stale ones among them, the pushes and the edges looked at. on the page's graph from 0 the vertices settle 0, 2, 1, 3, 4, 5 in 8 pops, 2 of them stale, and 8 pushes, over 18 looks. a menu picks the source, another goes back to the page's graph, and a button makes a new random graph.

try it

four calls the run makes over and over: which vertex comes out next, what a relax does to a distance, whether an entry is stale, and what the shortest distance is in the end. make them.

0 has settled at 0, and its edges are relaxed. which vertex comes out of the heap and settles next? tap it.

412586321012345041∞∞∞
heap(1, 2)(4, 1)top

tap a vertex.

0 / 0 right

a practice exercise on small weighted graphs, drawn with the weights on the edges: the page's graph first, then random ones of 5 or 6 vertices on a circle. some questions show a run partway, with each vertex's distance so far and the heap's entries in a strip, smallest first, and ask which vertex comes out and settles next, answered by tapping it: a stale entry at the front of the heap is the trap. others say a vertex has just settled, light an edge out of it and give the neighbor's distance so far, and ask for the neighbor's distance after the relax, with the sum, the weight alone, and the neighbor's distance so far, or the settled vertex's own when there's none, as the choices. others show the entry the heap just handed out, above the rest of the heap, with its vertex's distance, and ask whether it's stale. the rest show a graph alone, the source ringed cyan and a vertex ringed amber, and ask for the shortest distance between them, with other ways in and near misses as the other choices.

pseudocode

pseudocode
dijkstra(adj, src):  # adj[u] holds (v, w) for each edge u → v, w >= 0
  dist = [-1] * n; parent = [-1] * n; done = [false] * n
  dist[src] = 0; heap = [(0, src)]  # (dist, vertex) entries, smallest first
  while heap:
    d, u = pop(heap)  # the closest vertex not settled yet
    if done[u]: continue  # stale: u settled with a smaller dist already
    done[u] = true  # dist[u] is final
    for v, w in adj[u]:
      if done[v]: continue
      if dist[v] == -1 or d + w < dist[v]:  # found, or found a shorter way
        dist[v] = d + w; parent[v] = u
        push(heap, (dist[v], v))  # an older entry for v goes stale
  return dist, parent

path_to(found, v):
  if found.dist[v] == -1: return []
  path = []
  while v != -1: path.append(v); v = found.parent[v]
  return reversed(path)

the heap holds (dist, vertex) pairs, so the smallest dist comes out first, and on a tie the smaller vertex. a vertex can be in the heap more than once: a shorter way pushes a new pair and leaves the old one where it is. the done check right after the pop is what skips the old one. the relax is strict, d + w < dist[v]: a tie changes nothing, so a vertex’s parent is the one that settled first among its equals. path_to walks the parents back from v and reverses, as on the bfs page.

the relax and the settle, up close

a look along an edge ends one of five ways. here’s the first of each in the run from 0, with each vertex’s dist so far above it, and how many of the run’s 18 looks ended that way:

  • 12010

    done · 9 of 18
    0 is settled already: skip it, with no sum

  • 4010∞

    found · 5 of 18
    1 had no dist: 0 + 4 = 4, parent 0. push (4, 1)

  • 22114

    closer · 2 of 18
    1 + 2 = 3 beats 4: dist[1] = 3, parent 2. push (3, 1)

  • 145910

    a tie · 1 of 18
    9 + 1 = 10 ties 10: not shorter, so 5 keeps parent 3

  • 33489

    longer · 1 of 18
    8 + 3 = 11 is more than 9: nothing changes

the five kinds of look the run from 0 makes on the page's graph, each drawn as two vertices and the edge between them with its weight: the settled vertex on the left, the neighbor on the right, each with its distance so far. done: 2 looks along 2 to 0, and 0 is settled already, so it's skipped with no sum, 9 of the 18 looks. found: 0 to 1 costs 4, and 1 had no distance, so 0 + 4 = 4, parent 0, and (4, 1) goes in, 5 of the 18. closer: 2 to 1 costs 2, and 1 + 2 = 3 beats 4, so 1 drops to 3 with parent 2 and (3, 1) goes in, 2 of the 18. a tie: 4 to 5 costs 1, and 9 + 1 = 10 ties 10, so 5 keeps parent 3, once. longer: 3 to 4 costs 3, and 8 + 3 = 11 is more than 9, so nothing changes, once.

the edge 2 → 1 costs
1250120∞∞
poppedheap-(0, 0)top

dist[0] = 0, and (0, 0) goes in the heap. nothing else is found yet

the way to 1 through 2
2 + 5 = 7
dijkstra says dist[1] is
1
bellman-ford says
1

three vertices in a triangle, with arrows: 0 to 1 costs 1, 0 to 2 costs 2, and 2 to 1 costs 5, with a switch that makes it -5. the run plays the same either way, a step at a time, with each vertex's distance and the heap's entries: 0 settles and finds 1 at 1 and 2 at 2, 1 settles at 1 with (2, 2) still in the heap, then 2 settles and looks along 2 to 1, but 1 is done, so nothing changes. a readout gives the way to 1 through 2, dijkstra's answer for 1 and bellman-ford's. with the 5, the way through 2 costs 2 + 5 = 7, and both say 1. with the -5, it costs 2 - 5 = -3: bellman-ford says -3, and dijkstra still says 1, marked wrong.

complexity

binary heaparray scan
timeO((n + m) log n)O(n² + m)
heap entriesat most m + 1none
extra spaceO(n + m)O(n)
better whenm is small next to n²m is near n²

m counts edges the way the lists do: an undirected edge is two, one each way. every edge out of a settled vertex is looked at once: m looks. each look that lowers a dist is a push, and every push is popped once, each at most log₂ of the heap’s size deep: at most m + 1 of each. with the n vertices that’s O((n + m) log n), and O(m log n) when every vertex is reached. the array scan drops the heap and finds the closest unsettled vertex by reading all n of them, once per settled vertex: n², plus the same m looks. on a sparse graph, roads or links, m is a few times n and the heap wins by a lot. on a dense one m is near n², the looks dwarf everything else, and the scan is as good with less to keep.

05101520162564096array scan
pushes and pops
2.41 steps per vertex
swaps in the heap
11.3 steps per vertex
array scan
4,021 steps per vertex

a line chart of steps per vertex against how many vertices there are, from 16 to 4,096 on a doubling scale, each graph with 4 edges out of each vertex on average, with the top at 20 and a slider that picks a size and reads off every line. pushes and pops, solid cyan, stay flat, between 2.3 and 2.7 per vertex at every size. the swaps inside the heap, dashed cyan, climb by about one each time the vertices double: 2.69 at 16 and 11.3 at 4,096, a straight line on this axis, which is the log. the array version's scan, dashed amber, reads every vertex once a round, so about n per vertex: 17 at 16, and off the top of the chart before 32.

on a graph of 4,096 vertices and 16,384 edges, the heap took 4,932 pushes and 4,932 pops, 912 of them stale, and 46,269 swaps inside the heap, about 11 per vertex. the array scan read 16,470,016 cells: 4,021 rounds of 4,096. at 16 vertices and 64 edges it’s 43 swaps against 272 cells. per vertex, the pushes and pops stay flat, between 2.3 and 2.7 whatever the size, and the swaps climb by about one each time the graph doubles: that’s the log. a dense graph flips it: with 1,024 vertices and 1,047,552 edges, the 1,047,552 looks dwarf both the heap’s 27,326 swaps and the scan’s 1,049,600 cells, so the heap buys nothing there.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded weighted graphs against bellman-ford, and a 3-vertex graph with one negative edge where every tab gives the same wrong answer, 1 where the true distance is -3. every tab writes out its own binary heap, orders it by dist and then by vertex, and relaxes with a strict less-than, so they all settle the vertices in the same order and return the same parents: on the page’s graph, 5’s parent is 3, not 4. a vertex it never reaches has a dist of -1 in typescript, go, c and python, None in rust and nil in swift. a source that isn’t a vertex: typescript throws a RangeError, python raises an IndexError, swift stops on a precondition, go and rust panic when they index with it, and c returns false.

go/algos/dijkstra/dijkstra.go
// Package dijkstra is a reference dijkstra: shortest paths from one vertex to every other, over edges with
// non-negative weights. the closest vertex that isn't settled yet is settled next, and a settled vertex
// never gets closer: every path still open starts at least as far out, and no weight can bring it back
// down. a binary min-heap hands out the closest vertex. it's written out here, so the file stands alone.
package dijkstra

import "slices"

// Edge is an edge out of a vertex: where it goes, and what it costs. Weights are non-negative integers,
// and a path's total weight has to fit in an int.
type Edge struct {
	To, Weight int
}

// Found is what the search found: Dist[v], how far v is from the source, and Parent[v], the vertex before
// v on that path. Both are -1 for a vertex it never reached.
type Found struct {
	Dist   []int
	Parent []int
}

// entry is a heap entry: a vertex, and the dist it was pushed with.
type entry struct{ dist, vertex int }

// less reports whether a comes off the heap before b: smaller dist first, and on a tie the smaller vertex,
// so every run pops in one order.
func less(a, b entry) bool {
	return a.dist < b.dist || a.dist == b.dist && a.vertex < b.vertex
}

// minHeap is a binary min-heap of entries in a slice: entry i's children are at 2i + 1 and 2i + 2.
type minHeap []entry

// push puts e in at the end and sifts it up while its parent is bigger.
func (h *minHeap) push(e entry) {
	*h = append(*h, e)
	s := *h
	for i := len(s) - 1; i > 0; {
		parent := (i - 1) / 2
		if !less(s[i], s[parent]) {
			return
		}
		s[i], s[parent] = s[parent], s[i]
		i = parent
	}
}

// pop takes off the smallest entry. The last one moves to the top and sifts down past its smaller child.
func (h *minHeap) pop() entry {
	s := *h
	top := s[0]
	last := len(s) - 1
	s[0] = s[last]
	s = s[:last]
	*h = s
	for i := 0; ; {
		left, right := 2*i+1, 2*i+2
		small := i
		if left < len(s) && less(s[left], s[small]) {
			small = left
		}
		if right < len(s) && less(s[right], s[small]) {
			small = right
		}
		if small == i {
			return top
		}
		s[i], s[small] = s[small], s[i]
		i = small
	}
}

// ShortestPaths returns the shortest paths from src. adj[u] holds an Edge for each edge u -> v of weight
// w; an undirected edge is two entries. Dist[src] is 0 and Parent[src] is -1, and a vertex it never
// reaches keeps -1 for both. The heap holds (dist, vertex) entries. When a shorter way to a vertex turns
// up, a new entry goes in and the old one stays: it's stale, and it's skipped when it comes out, since the
// vertex is done by then. A src outside 0 to n - 1 is a bug, and indexing with it panics.
func ShortestPaths(adj [][]Edge, src int) Found {
	n := len(adj)
	dist := make([]int, n)
	parent := make([]int, n)
	for v := range n {
		dist[v], parent[v] = -1, -1 // -1: not reached yet
	}
	done := make([]bool, n)
	var heap minHeap
	dist[src] = 0
	heap.push(entry{0, src})
	for len(heap) > 0 {
		next := heap.pop()
		d, u := next.dist, next.vertex
		if done[u] {
			continue // stale: u settled with a smaller dist already
		}
		done[u] = true // dist[u] is final: everything left in the heap is at least d, and weights only add
		for _, e := range adj[u] {
			v, w := e.To, e.Weight
			if done[v] {
				continue
			}
			if dist[v] == -1 || d+w < dist[v] {
				dist[v] = d + w
				parent[v] = u
				heap.push(entry{dist[v], v})
			}
		}
	}
	return Found{Dist: dist, Parent: parent}
}

// PathTo returns the path from the source to v, through the parents: the source first, v last. It's empty
// when v wasn't reached, and just the source for the source. A v outside 0 to n - 1 panics, as src does.
func (f Found) PathTo(v int) []int {
	if f.Dist[v] == -1 {
		return nil
	}
	var path []int
	for u := v; u != -1; u = f.Parent[u] {
		path = append(path, u)
	}
	slices.Reverse(path)
	return path
}
rust/algos/src/dijkstra.rs
//! dijkstra's shortest paths: from one vertex to every other, over edges with non-negative weights. the closest vertex that isn't settled yet is settled next, and a settled vertex never gets closer: every path still open starts at least as far out, and no weight can bring it back down. a binary min-heap hands out the closest vertex. it's written out here, so the file stands alone. weights and distances are i64s, so a path's total has to fit in one.

/// An edge out of a vertex: where it goes, and what it costs. Weights are non-negative integers.
pub type Edge = (usize, i64);

/// `dist[v]` from the source, and `parent[v]`, the vertex before `v` on that path. `None` for a
/// vertex it never reached, and the source's parent is `None` too.
#[derive(Debug, PartialEq)]
pub struct Found {
    pub dist: Vec<Option<i64>>,
    pub parent: Vec<Option<usize>>,
}

/// A heap entry: the dist it was pushed with, then the vertex. Tuples compare field by field, so a
/// smaller dist comes first, and on a tie the smaller vertex: every run pops in one order.
type Entry = (i64, usize);

/// An entry goes in at the end and sifts up while its parent is bigger.
fn push(heap: &mut Vec<Entry>, entry: Entry) {
    heap.push(entry);
    let mut i = heap.len() - 1;
    while i > 0 {
        let parent = (i - 1) / 2;
        if heap[parent] <= heap[i] {
            return;
        }
        heap.swap(parent, i);
        i = parent;
    }
}

/// The smallest entry comes off the top. The last one moves up there and sifts down past its
/// smaller child. `None` when the heap is empty.
fn pop(heap: &mut Vec<Entry>) -> Option<Entry> {
    if heap.is_empty() {
        return None;
    }
    let top = heap.swap_remove(0); // the last entry fills slot 0
    let mut i = 0;
    loop {
        let mut small = i;
        for c in [2 * i + 1, 2 * i + 2] {
            if c < heap.len() && heap[c] < heap[small] {
                small = c;
            }
        }
        if small == i {
            return Some(top);
        }
        heap.swap(i, small);
        i = small;
    }
}

/// Shortest paths from `src`. `adj[u]` holds `(v, w)` for each edge u → v of weight w; an
/// undirected edge is two entries. `dist[src]` is 0 and `parent[src]` is `None`, and a vertex it
/// never reaches keeps `None` for both. The heap holds (dist, vertex) entries. When a shorter way
/// to a vertex turns up, a new entry goes in and the old one stays: it's stale, and it's skipped
/// when it comes out, since the vertex is done by then. A `src` past n - 1 panics, as any index
/// out of range does: there's no check of its own.
pub fn dijkstra(adj: &[Vec<Edge>], src: usize) -> Found {
    let n = adj.len();
    let mut dist = vec![None; n];
    let mut parent = vec![None; n];
    let mut done = vec![false; n];
    let mut heap = Vec::new();
    dist[src] = Some(0);
    push(&mut heap, (0, src));
    while let Some((d, u)) = pop(&mut heap) {
        if done[u] {
            continue; // stale: u settled with a smaller dist already
        }
        // dist[u] is final: everything left in the heap is at least d, and weights only add
        done[u] = true;
        for &(v, w) in &adj[u] {
            if done[v] {
                continue;
            }
            if dist[v].is_none_or(|dv| d + w < dv) {
                dist[v] = Some(d + w);
                parent[v] = Some(u);
                push(&mut heap, (d + w, v));
            }
        }
    }
    Found { dist, parent }
}

/// The path from the source to `v`, through the parents. Empty when `v` wasn't reached, and just
/// the source for the source. A `v` past the last vertex panics, as any index out of range does.
pub fn path_to(found: &Found, v: usize) -> Vec<usize> {
    if found.dist[v].is_none() {
        return Vec::new();
    }
    let mut path = Vec::new();
    let mut at = Some(v);
    while let Some(u) = at {
        path.push(u);
        at = found.parent[u];
    }
    path.reverse();
    path
}

#[cfg(test)]
mod tests {
    use super::*;

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    // the page's graph: 6 vertices and 9 edges with no direction, as (u, v, weight)
    const PAGE: [(usize, usize, i64); 9] = [
        (0, 1, 4),
        (0, 2, 1),
        (1, 2, 2),
        (1, 3, 5),
        (2, 3, 8),
        (1, 4, 6),
        (3, 4, 3),
        (3, 5, 2),
        (4, 5, 1),
    ];

    /// Adjacency lists from edges with no direction: each edge is an entry on both ends, in the
    /// order given.
    fn undirected(n: usize, edges: &[(usize, usize, i64)]) -> Vec<Vec<Edge>> {
        let mut adj = vec![Vec::new(); n];
        for &(u, v, w) in edges {
            adj[u].push((v, w));
            adj[v].push((u, w));
        }
        adj
    }

    /// Bellman-ford: relax every edge until nothing changes. Slow, and right with negative
    /// weights too.
    fn bellman_ford(adj: &[Vec<Edge>], src: usize) -> Vec<Option<i64>> {
        let n = adj.len();
        let mut dist = vec![None; n];
        dist[src] = Some(0);
        for _ in 1..n {
            let mut changed = false;
            for u in 0..n {
                let Some(du) = dist[u] else { continue };
                for &(v, w) in &adj[u] {
                    if dist[v].is_none_or(|dv| du + w < dv) {
                        dist[v] = Some(du + w);
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
        }
        dist
    }

    #[test]
    fn the_pages_graph_from_0_dist_0_3_1_8_9_10_and_the_direct_edge_0_to_1_of_4_loses_to_1_plus_2()
    {
        assert_eq!(
            dijkstra(&undirected(6, &PAGE), 0),
            Found {
                dist: vec![Some(0), Some(3), Some(1), Some(8), Some(9), Some(10)],
                parent: vec![None, Some(2), Some(0), Some(1), Some(1), Some(3)],
            }
        );
    }

    #[test]
    fn path_to_on_it_0_2_1_3_5_to_5_0_2_1_4_to_4_and_0_alone_for_the_source() {
        let found = dijkstra(&undirected(6, &PAGE), 0);
        assert_eq!(
            [path_to(&found, 5), path_to(&found, 4), path_to(&found, 0)],
            [vec![0, 2, 1, 3, 5], vec![0, 2, 1, 4], vec![0]]
        );
    }

    #[test]
    fn one_vertex_a_vertex_it_cant_reach_and_a_source_that_isnt_there_panics() {
        assert_eq!(
            dijkstra(&[vec![]], 0),
            Found {
                dist: vec![Some(0)],
                parent: vec![None],
            }
        );
        // the only edge points at the source, so 1 stays unreached
        let found = dijkstra(&[vec![], vec![(0, 3)]], 0);
        assert_eq!(
            found,
            Found {
                dist: vec![Some(0), None],
                parent: vec![None, None],
            }
        );
        assert_eq!(path_to(&found, 1), vec![]);
        assert!(std::panic::catch_unwind(|| dijkstra(&[vec![]], 1)).is_err());
    }

    #[test]
    fn a_zero_weight_edge_two_zeros_in_a_row_beat_a_direct_1() {
        let adj = [vec![(1, 0), (2, 1)], vec![(2, 0)], vec![]];
        assert_eq!(
            dijkstra(&adj, 0),
            Found {
                dist: vec![Some(0), Some(0), Some(0)],
                parent: vec![None, Some(0), Some(1)],
            }
        );
    }

    #[test]
    fn a_tie_two_equal_paths_and_the_parent_is_the_one_that_settled_first() {
        // a diamond, every edge 1: 3 is at 2 through 1 or 2. 1 settles first, so it's the parent,
        // however adj[0] is ordered
        let diamond = [vec![(2, 1), (1, 1)], vec![(3, 1)], vec![(3, 1)], vec![]];
        assert_eq!(
            dijkstra(&diamond, 0),
            Found {
                dist: vec![Some(0), Some(1), Some(1), Some(2)],
                parent: vec![None, Some(0), Some(0), Some(1)],
            }
        );
        // 2 settles at 1, before 1 settles at 3: both reach 3 at 4, and 2 got there first
        let skewed = [vec![(1, 3), (2, 1)], vec![(3, 1)], vec![(3, 3)], vec![]];
        assert_eq!(
            dijkstra(&skewed, 0),
            Found {
                dist: vec![Some(0), Some(3), Some(1), Some(4)],
                parent: vec![None, Some(0), Some(0), Some(2)],
            }
        );
    }

    #[test]
    fn agrees_with_bellman_ford_on_2000_seeded_directed_graphs_and_every_parent_edge_is_tight() {
        let mut next = xorshift32(42);
        for _ in 0..2000 {
            let n = 1 + next() % 30;
            let mut adj = vec![Vec::new(); n];
            for _ in 0..next() % (3 * n) {
                adj[next() % n].push((next() % n, (next() % 10) as i64));
            }
            let src = next() % n;
            let found = dijkstra(&adj, src);
            assert_eq!(found.dist, bellman_ford(&adj, src));
            assert_eq!(found.parent[src], None);
            for v in (0..n).filter(|&v| v != src) {
                let Some(dv) = found.dist[v] else {
                    assert_eq!(found.parent[v], None);
                    assert_eq!(path_to(&found, v), vec![]);
                    continue;
                };
                let p = found.parent[v].expect("a reached vertex has a parent");
                // some edge from the parent closes the gap exactly
                assert!(
                    adj[p]
                        .iter()
                        .any(|&(to, w)| to == v && found.dist[p].is_some_and(|dp| dp + w == dv))
                );
                let path = path_to(&found, v);
                assert_eq!((path[0], path[path.len() - 1]), (src, v));
            }
        }
    }

    #[test]
    fn a_negative_edge_1_settles_at_1_before_the_way_through_2_which_costs_minus_3_is_seen() {
        let adj = [vec![(1, 1), (2, 2)], vec![], vec![(1, -5)]];
        assert_eq!(
            dijkstra(&adj, 0),
            Found {
                dist: vec![Some(0), Some(1), Some(2)],
                parent: vec![None, Some(0), Some(0)],
            }
        );
        assert_eq!(bellman_ford(&adj, 0), [Some(0), Some(-3), Some(2)]);
    }
}
site/src/visuals/dijkstra/dijkstra.ts
/**
 * Dijkstra's shortest paths: from one vertex to every other, over edges with non-negative weights. The
 * closest vertex that isn't settled yet is settled next, and a settled vertex never gets closer: every path
 * still open starts at least as far out, and no weight can bring it back down. A binary min-heap hands out
 * the closest vertex. It's written out here, so the file stands alone.
 */

/** An edge out of a vertex: where it goes, and what it costs. Weights are non-negative integers. */
export type Edge = readonly [to: number, weight: number];
/** dist[v] from the source, and parent[v], the vertex before v on that path. -1 for a vertex it never
 * reached. */
export type Found = { dist: number[]; parent: number[] };

/** A heap entry: a vertex, and the dist it was pushed with. */
type Entry = readonly [dist: number, vertex: number];

/** Smaller dist first, and on a tie the smaller vertex, so every run pops in one order. */
const less = (a: Entry, b: Entry) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);

/** An entry goes in at the end and sifts up while its parent is bigger. */
function push(heap: Entry[], entry: Entry) {
  heap.push(entry);
  let i = heap.length - 1;
  while (i > 0) {
    const p = Math.floor((i - 1) / 2);
    if (!less(heap[i], heap[p])) return;
    [heap[i], heap[p]] = [heap[p], heap[i]];
    i = p;
  }
}

/** The smallest entry comes off the top. The last one moves up there and sifts down past its smaller
 * child. */
function pop(heap: Entry[]): Entry {
  const top = heap[0];
  const last = heap.pop()!;
  if (heap.length === 0) return top;
  heap[0] = last;
  let i = 0;
  for (;;) {
    let small = i;
    for (const c of [2 * i + 1, 2 * i + 2]) if (c < heap.length && less(heap[c], heap[small])) small = c;
    if (small === i) return top;
    [heap[i], heap[small]] = [heap[small], heap[i]];
    i = small;
  }
}

/**
 * Shortest paths from src. adj[u] holds [v, w] for each edge u → v of weight w; an undirected edge is two
 * entries. dist[src] is 0 and parent[src] is -1, and a vertex it never reaches keeps -1 for both. The heap
 * holds [dist, vertex] entries. When a shorter way to a vertex turns up, a new entry goes in and the old one
 * stays: it's stale, and it's skipped when it comes out, since the vertex is done by then.
 */
export function dijkstra(adj: readonly (readonly Edge[])[], src: number): Found {
  const n = adj.length;
  if (!Number.isInteger(src) || src < 0 || src >= n) throw new RangeError(`no vertex ${src}`);
  const dist = Array<number>(n).fill(-1);
  const parent = Array<number>(n).fill(-1);
  const done = Array<boolean>(n).fill(false);
  const heap: Entry[] = [];
  dist[src] = 0;
  push(heap, [0, src]);
  while (heap.length > 0) {
    const [d, u] = pop(heap);
    if (done[u]) continue; // stale: u settled with a smaller dist already
    done[u] = true; // dist[u] is final: everything left in the heap is at least d, and weights only add
    for (const [v, w] of adj[u]) {
      if (done[v]) continue;
      if (dist[v] === -1 || d + w < dist[v]) {
        dist[v] = d + w;
        parent[v] = u;
        push(heap, [dist[v], v]);
      }
    }
  }
  return { dist, parent };
}

/** The path from the source to v, through the parents. [] when v wasn't reached, and [src] for the source. */
export function pathTo(found: Found, v: number): number[] {
  if (!Number.isInteger(v) || v < 0 || v >= found.dist.length) throw new RangeError(`no vertex ${v}`);
  if (found.dist[v] === -1) return [];
  const path: number[] = [];
  for (let u = v; u !== -1; u = found.parent[u]) path.push(u);
  return path.reverse();
}
c/algos/dijkstra.c
/* dijkstra's shortest paths: from one vertex to every other, over edges with non-negative weights. the closest vertex that isn't settled yet is settled next, and a settled vertex never gets closer: every path still open starts at least as far out, and no weight can bring it back down. a binary min-heap hands out the closest vertex. it's written out here, so the file stands alone. */
#include "dijkstra.h"

#include <stdlib.h>

/* a heap entry: a vertex, and the dist it was pushed with */
typedef struct {
    int dist;
    size_t vertex;
} Entry;

/* len entries in an array read as a tree: items[0] is the top, and entry i's children are at
   2i + 1 and 2i + 2. every parent comes before its children. it never grows: dijkstra_run gives it
   room for every push there can be */
typedef struct {
    Entry *items;
    size_t len;
} Heap;

/* smaller dist first, and on a tie the smaller vertex, so every run pops in one order */
static bool before(Entry a, Entry b) {
    return a.dist < b.dist || (a.dist == b.dist && a.vertex < b.vertex);
}

static void swap(Entry *a, Entry *b) {
    Entry t = *a;
    *a = *b;
    *b = t;
}

/* an entry goes in at the end and swaps up while it comes before its parent */
static void push(Heap *h, Entry e) {
    size_t i = h->len++;
    h->items[i] = e;
    while (i > 0) {
        size_t parent = (i - 1) / 2;
        if (!before(h->items[i], h->items[parent])) return;
        swap(&h->items[i], &h->items[parent]);
        i = parent;
    }
}

/* the first entry comes off the top. the last one moves up there and swaps down past children that
   come before it. the heap must not be empty: if the top was the only entry, the last one is itself,
   and the swap down stops right away */
static Entry pop(Heap *h) {
    Entry top = h->items[0];
    h->items[0] = h->items[--h->len];
    size_t i = 0;
    for (;;) {
        size_t left = 2 * i + 1, right = left + 1, first = i;
        if (left < h->len && before(h->items[left], h->items[first])) first = left;
        if (right < h->len && before(h->items[right], h->items[first])) first = right;
        if (first == i) return top;
        swap(&h->items[i], &h->items[first]);
        i = first;
    }
}

/* the heap holds (dist, vertex) entries. when a shorter way to a vertex turns up, a new entry goes
   in and the old one stays: it's stale, and it's skipped when it comes out, since the vertex is
   done by then. there's one push for the source and at most one per edge, since a vertex's edges
   are looked at once, when it's settled, so m + 1 slots hold every entry, m being the edges. once
   src is below n, n is at least 1, so none of the allocations is one of 0 bytes */
bool dijkstra_run(DijkstraTree *tree, const DijkstraEdge *const *adj, const size_t *len, size_t n, size_t src) {
    *tree = (DijkstraTree){0};
    if (src >= n) return false; /* no such vertex */
    size_t m = 0;
    for (size_t u = 0; u < n; u++) m += len[u];
    tree->dist = malloc(n * sizeof *tree->dist);
    tree->parent = malloc(n * sizeof *tree->parent);
    bool *done = calloc(n, sizeof *done); /* calloc: nothing settled yet */
    Heap heap = {malloc((m + 1) * sizeof *heap.items), 0};
    if (!tree->dist || !tree->parent || !done || !heap.items) {
        free(done);
        free(heap.items);
        dijkstra_free(tree); /* frees whichever of the two were allocated: free(NULL) does nothing */
        return false;
    }
    tree->n = n;
    for (size_t v = 0; v < n; v++) tree->dist[v] = tree->parent[v] = -1; /* nothing reached yet */
    tree->dist[src] = 0;
    push(&heap, (Entry){0, src});
    while (heap.len > 0) {
        Entry e = pop(&heap);
        size_t u = e.vertex;
        if (done[u]) continue; /* stale: u settled with a smaller dist already */
        /* dist[u] is final: everything left in the heap is at least e.dist, and weights only add */
        done[u] = true;
        for (size_t i = 0; i < len[u]; i++) {
            size_t v = adj[u][i].to;
            int d = e.dist + adj[u][i].weight;
            if (done[v]) continue;
            if (tree->dist[v] == -1 || d < tree->dist[v]) {
                tree->dist[v] = d;
                tree->parent[v] = (int)u;
                push(&heap, (Entry){d, v});
            }
        }
    }
    free(done);
    free(heap.items);
    return true;
}

void dijkstra_free(DijkstraTree *tree) {
    free(tree->dist);
    free(tree->parent);
    *tree = (DijkstraTree){0}; /* no vertices */
}

/* follows parents from v back to the source, writing as it goes, then reverses out in place so the
   source comes first. a reached v writes itself at least, so k is 1 or more and k - 1 can't wrap */
bool dijkstra_path_to(const DijkstraTree *tree, size_t v, size_t *out, size_t *count) {
    *count = 0;
    if (v >= tree->n) return false; /* no such vertex */
    if (tree->dist[v] == -1) return true; /* never reached: no path */
    size_t k = 0;
    for (int u = (int)v; u != -1; u = tree->parent[u]) out[k++] = (size_t)u;
    for (size_t i = 0, j = k - 1; i < j; i++, j--) {
        size_t t = out[i];
        out[i] = out[j];
        out[j] = t;
    }
    *count = k;
    return true;
}
swift/algos/Dijkstra.swift
/// dijkstra's shortest paths: from one vertex to every other, over edges with non-negative weights. the closest vertex that isn't settled yet is settled next, and a settled vertex never gets closer: every path still open starts at least as far out, and no weight can bring it back down. a binary min-heap hands out the closest vertex. it's written out here, so the file stands alone. weights and distances are Ints, so a path's total has to fit in one, or swift traps.

/// dist[v] from the source, and parent[v], the vertex before v on that path. nil for a vertex it never reached, and
/// the source's parent is nil too
public struct DijkstraTree {
    public let dist: [Int?]
    public let parent: [Int?]

    /// the path from the source to v, through the parents. [] when v wasn't reached, and [src] for the source. a v
    /// outside the tree traps
    public func path(to v: Int) -> [Int] {
        precondition(0 <= v && v < dist.count, "no vertex \(v)")
        if dist[v] == nil { return [] }
        var path = [v]
        while let p = parent[path.last!] { path.append(p) } // the source has no parent, so the walk stops there
        return path.reversed()
    }
}

// a heap entry: a vertex, and the dist it was pushed with. tuples compare in order: smaller dist first, and on a tie
// the smaller vertex, so every run pops in one order
private typealias Entry = (dist: Int, vertex: Int)

// an entry goes in at the end and sifts up while its parent is bigger
private func push(_ heap: inout [Entry], _ entry: Entry) {
    heap.append(entry)
    var i = heap.count - 1
    while i > 0 {
        let p = (i - 1) / 2
        if !(heap[i] < heap[p]) { return }
        heap.swapAt(i, p)
        i = p
    }
}

// the smallest entry comes off the top. the last one moves up there and sifts down past its smaller child
private func pop(_ heap: inout [Entry]) -> Entry {
    let top = heap[0]
    let last = heap.removeLast()
    if heap.isEmpty { return top }
    heap[0] = last
    var i = 0
    while true {
        let left = 2 * i + 1
        let right = left + 1
        var small = i
        if left < heap.count && heap[left] < heap[small] { small = left }
        if right < heap.count && heap[right] < heap[small] { small = right }
        if small == i { return top }
        heap.swapAt(i, small)
        i = small
    }
}

/// shortest paths from src. adj[u] holds (v, w) for each edge u -> v of weight w; an undirected edge is two entries.
/// dist[src] is 0 and parent[src] is nil, and a vertex it never reaches keeps nil for both. the heap holds (dist,
/// vertex) entries. when a shorter way to a vertex turns up, a new entry goes in and the old one stays: it's stale,
/// and it's skipped when it comes out, since the vertex is done by then. a src outside 0 to n - 1 traps
public func dijkstra(_ adj: [[(to: Int, weight: Int)]], _ src: Int) -> DijkstraTree {
    let n = adj.count
    precondition(0 <= src && src < n, "no vertex \(src)")
    var dist = [Int?](repeating: nil, count: n)
    var parent = [Int?](repeating: nil, count: n)
    var done = [Bool](repeating: false, count: n)
    var heap: [Entry] = []
    dist[src] = 0
    push(&heap, (0, src))
    while !heap.isEmpty {
        let (d, u) = pop(&heap)
        if done[u] { continue } // stale: u settled with a smaller dist already
        done[u] = true // dist[u] is final: everything left in the heap is at least d, and weights only add
        for (v, w) in adj[u] {
            if done[v] { continue }
            if dist[v] == nil || d + w < dist[v]! {
                dist[v] = d + w
                parent[v] = u
                push(&heap, (d + w, v))
            }
        }
    }
    return DijkstraTree(dist: dist, parent: parent)
}
python/algos/dijkstra.py
"""dijkstra's shortest paths: from one vertex to every other, over edges with non-negative weights. the closest vertex that isn't settled yet is settled next, and a settled vertex never gets closer: every path still open starts at least as far out, and no weight can bring it back down. a binary min-heap hands out the closest vertex. it's written out here, so the file stands alone. a path's total weight is a python int, which grows as it needs to, so it can't overflow."""

from __future__ import annotations

from typing import NamedTuple

# an edge out of a vertex: where it goes, and what it costs. weights are non-negative ints
Edge = tuple[int, int]

# a heap entry: the dist a vertex was pushed with, then the vertex. tuples compare item by item, so the
# smaller dist comes out first, and on a tie the smaller vertex: every run pops in one order
Entry = tuple[int, int]


class Found(NamedTuple):
    """dist[v] from the source, and parent[v], the vertex before v on that path.

    -1 for both when a vertex was never reached.
    """

    dist: list[int]
    parent: list[int]


def _push(heap: list[Entry], entry: Entry) -> None:
    """Add entry at the end, then swap it up while it's smaller than its parent."""
    heap.append(entry)
    i = len(heap) - 1
    while i > 0:
        parent = (i - 1) // 2
        if heap[parent] <= heap[i]:
            return
        heap[parent], heap[i] = heap[i], heap[parent]
        i = parent


def _pop(heap: list[Entry]) -> Entry:
    """Take out the smallest entry: the last one moves to the top and swaps down past its smaller child."""
    top = heap[0]
    last = heap.pop()  # only the last slot can go without leaving a hole
    if heap:  # unless that was the only entry
        heap[0] = last
        n = len(heap)
        i = 0
        while True:
            left = 2 * i + 1
            right = left + 1
            small = i
            if left < n and heap[left] < heap[small]:
                small = left
            if right < n and heap[right] < heap[small]:
                small = right
            if small == i:
                break
            heap[i], heap[small] = heap[small], heap[i]
            i = small
    return top


def dijkstra(adj: list[list[Edge]], src: int) -> Found:
    """Return the shortest paths from src.

    adj[u] holds (v, w) for each edge u -> v of weight w; an undirected edge is two entries. dist[src] is 0
    and parent[src] is -1, and a vertex it never reaches keeps -1 for both. The heap holds (dist, vertex)
    entries. When a shorter way to a vertex turns up, a new entry goes in and the old one stays: it's stale,
    and it's skipped when it comes out, since the vertex is done by then. A src outside 0 to n - 1 raises
    IndexError.
    """
    n = len(adj)
    if not 0 <= src < n:
        raise IndexError(f"no vertex {src}")  # a negative src would count from the end of the list
    dist = [-1] * n
    parent = [-1] * n
    done = [False] * n
    heap: list[Entry] = []
    dist[src] = 0
    _push(heap, (0, src))
    while heap:
        d, u = _pop(heap)
        if done[u]:
            continue  # stale: u settled with a smaller dist already
        done[u] = True  # dist[u] is final: everything left in the heap is at least d, and weights only add
        for v, w in adj[u]:
            if done[v]:
                continue
            if dist[v] == -1 or d + w < dist[v]:
                dist[v] = d + w
                parent[v] = u
                _push(heap, (dist[v], v))
    return Found(dist, parent)


def path_to(found: Found, v: int) -> list[int]:
    """Return the path from the source to v, through the parents.

    [] when v wasn't reached, and [src] for the source. A v outside 0 to n - 1 raises IndexError.
    """
    dist, parent = found
    if not 0 <= v < len(dist):
        raise IndexError(f"no vertex {v}")
    if dist[v] == -1:
        return []
    path = []
    u = v
    while u != -1:
        path.append(u)
        u = parent[u]
    path.reverse()
    return path

pitfalls

variants

practice

how real libraries do it

sources

  1. e. w. dijkstra, a note on two problems in connexion with graphs (opens in a new tab), numerische mathematik 1, 269–271, 1959. received in june 1959 and printed in december, three pages. ↩

  2. rfc 2328 (opens in a new tab), ospf version 2, section 16.1: a router calculates the shortest-path tree for its area with itself as the root, using the dijkstra algorithm. each iteration keeps a list of candidate vertices, ones with a path found but not necessarily the shortest; the candidate closest to the root is guaranteed shortest, so it moves to the tree and its neighbors are examined, and the algorithm ends when the list is empty. ↩ ↩2

  3. weighted.py (opens in a new tab) in networkx 3.7: _dijkstra_multisource keeps fringe as a heapq of (distance, c, node) with a counter c so nodes are never compared, pushes every source at 0, and after a pop skips a node already in dist with the comment “already searched this node”. further down (opens in a new tab), a shorter path to a node already in dist raises a ValueError about contradictory paths that asks whether the weights are negative, and a shorter way to an unsettled node pushes a new entry. its docstring (opens in a new tab) says the algorithm isn’t guaranteed to work with negative or floating point weights, and single_source_dijkstra (opens in a new tab) hands its one source to multi_source_dijkstra as a set. ↩ ↩2 ↩3

  4. binary_heap/mod.rs (opens in a new tab) at rust 1.99.1: the module’s example implements dijkstra’s algorithm for the shortest path problem on a directed graph. its Ord (opens in a new tab) flips the ordering on costs so the max-heap works as a min-heap, and compares positions on a tie. its comment (opens in a new tab) says the implementation isn’t memory-efficient, as it may leave duplicate nodes in the queue, and uses usize::MAX as a sentinel. the loop (opens in a new tab) returns at the goal, skips an entry whose cost is more than the node’s dist, with a comment that a better way may have been found already, and pushes a new state whenever a lower cost turns up. ↩ ↩2 ↩3

  5. example_pq_test.go (opens in a new tab) at go1.27.3: each item carries its index in the heap, which update needs and the heap.Interface methods maintain. update (opens in a new tab) sets the new priority and calls heap.Fix with that index. ↩ ↩2

  6. heapq.rst (opens in a new tab) in cpython 3.15.0, priority queue implementation notes: storing entries as (priority, count, task) makes the count a tie-breaker, so tasks with the same priority come out in the order they were added and two tasks are never compared. the rest of the notes (opens in a new tab) handle a changed priority by marking the old entry removed and pushing a new one, and pop_task skips removed entries. ↩ ↩2

  7. m. l. fredman and r. e. tarjan, fibonacci heaps and their uses in improved network optimization algorithms (opens in a new tab), journal of the acm 34(3), 596–615, 1987. the abstract: f-heaps do arbitrary deletion in O(log n) amortized time and every other heap operation, decrease-key among them, in O(1) amortized time, which brings dijkstra’s single-source shortest paths to O(n log n + m). ↩