From Dijkstra to BMSSP

September 08, 2025☕ 10 min read

Written in September 2025 as the start of a short series. Corrected and finished in November 2026: see the update at the end.

A few weeks ago I read an interesting paper titled "Breaking the Sorting Barrier for Directed Single-Source Shortest Paths" (Duan, Mao, Mao, Shu and Yin, 2025). Shortest path algorithms are everywhere: GPS apps, network routing, game AIs... and since the 80s, the best known bound for the general case (directed graphs, non-negative weights) was Dijkstra's algorithm with a Fibonacci heap. This paper beats it, with an algorithm called BMSSP ("Bounded Multi-Source Shortest Path").

"Beats" here means the bound: as graphs get bigger, BMSSP's running time grows more slowly than Dijkstra's. That's a statement about very large nn, with constant factors ignored. It doesn't promise that BMSSP is faster on any graph you'd actually run it on.

I wanted to write about it and implement it, but there are a few prerequisites for understanding the paper, and covering them all in one post would be too much. So this is the start of a short series, going from Dijkstra to BMSSP one prerequisite at a time: a refresher on Dijkstra, then the two pieces BMSSP borrows, edge relaxation and Bellman-Ford.

Throughout the post, nn is the number of vertices and mm the number of edges, like in the paper.

A quick Dijkstra refresher

Dijkstra finds single-source shortest paths: the shortest distance from one node ss to every other node, in a graph with non-negative edge weights1.

import heapq

def dijkstra(graph, start):
    dist = {node: float('inf') for node in graph}
    dist[start] = 0.0
    pq = [(0.0, start)]
    visited = set()

    while pq:
        d, u = heapq.heappop(pq)
        if u in visited:
            continue
        visited.add(u)
        for v, w in graph[u]:
            if v not in visited and d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(pq, (dist[v], v))

    return dist

It keeps three things:

  1. pq is a priority queue (a min-heap, heapq in Python) with the nodes we've reached but not finished yet. This is the frontier, and it's going to be important later.
  2. visited is the set of finished nodes.
  3. dist is our best known distance to each node. Everything starts at ∞\infty, except the source, at 00.

Then it runs the "extract min" loop: take the closest unfinished node, mark it as finished, and update its neighbours. The key assumption is that when a node comes out of the queue, its distance is final: with non-negative weights, nothing we find later can make it shorter. (This version skips the predecessor array, which you'd need to rebuild the actual path, since we only care about distances.)

For the undirected graph below:

ACEBDF2481035162
graph = {
    'A': [('B', 4), ('C', 2)],
    'B': [('A', 4), ('C', 1), ('D', 5)],
    'C': [('A', 2), ('B', 1), ('D', 8), ('E', 10)],
    'D': [('B', 5), ('C', 8), ('E', 2), ('F', 6)],
    'E': [('C', 10), ('D', 2), ('F', 3)],
    'F': [('D', 6), ('E', 3)]
}

print(dijkstra(graph, 'A'))
# {'A': 0.0, 'B': 3.0, 'C': 2.0, 'D': 8.0, 'E': 10.0, 'F': 13.0}

It would look like this:

Initial distances: {'A': 0, 'B': inf, 'C': inf, 'D': inf, 'E': inf, 'F': inf}

Iteration 1: Visiting A (distance: 0)
  Relaxed: B(4), C(2)
  Queue: [(2, 'C'), (4, 'B')]

Iteration 2: Visiting C (distance: 2)
  Relaxed: B(3), D(10), E(12)
  Queue: [(3, 'B'), (4, 'B'), (10, 'D'), (12, 'E')]

Iteration 3: Visiting B (distance: 3)
  Relaxed: D(8)
  Queue: [(4, 'B'), (8, 'D'), (10, 'D'), (12, 'E')]

Iteration 4: Visiting D (distance: 8), after skipping the stale (4, 'B')
  Relaxed: E(10), F(14)
  Queue: [(10, 'D'), (10, 'E'), (12, 'E'), (14, 'F')]

Iteration 5: Visiting E (distance: 10), after skipping the stale (10, 'D')
  Relaxed: F(13)
  Queue: [(12, 'E'), (13, 'F'), (14, 'F')]

Iteration 6: Visiting F (distance: 13), after skipping the stale (12, 'E')

Final distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}

Notice the stale entries like (4, 'B'): instead of updating a node's position in the heap, we push a new entry and skip the old one when it comes out. It's the simplest way to do it with heapq.

Where the cost comes from

Each node is finished once, and each edge pushes at most one entry, so with a binary heap Dijkstra runs in O(mlog⁡n)O(m \log n)2. With a Fibonacci heap it's O(m+nlog⁡n)O(m + n \log n), the bound that stood for decades (though in practice it's rarely worth it3).

The nlog⁡nn \log n term comes from the order in which Dijkstra finishes nodes: A, C, B, D, E, F, which is every node sorted by distance. On top of computing the distances, Dijkstra sorts the nodes by them, and sorting nn values by comparing them costs nlog⁡nn \log n. That's the sorting barrier4.

The paper gets around it because we never asked for the order, only for the distances. BMSSP computes the distances without fully sorting the nodes, in O(mlog⁡2/3n)O(m \log^{2/3} n). To see how, we need two more pieces.

Edge relaxation

Dijkstra repeatedly performs this operation:

if d + w < dist[v]:
    dist[v] = d + w

This is called edge relaxation: check whether going through uu and then taking the edge u→vu \to v beats our current best distance to vv, and if it does, update it. As a formula, d[v]=min⁡(d[v], d[u]+w(u,v))d[v] = \min(d[v],\ d[u] + w(u,v)). Think of it like this: distance estimates start too high (∞\infty) and gradually "relax" down toward their true values. They never go up.

Why does this work? The true shortest distances satisfy dist(v)≤dist(u)+w(u,v)dist(v) \le dist(u) + w(u,v) for every edge: the best route to vv can't be longer than the best route to uu plus one more edge. If an edge breaks that rule with our current estimates, our estimate for vv is wrong, and relaxing the edge fixes exactly that. When no edge breaks it, we're done. (Careful: this is not "the direct route is always shorter". In the graph above, the direct edge A→BA \to B costs 4, and the detour A→C→BA \to C \to B costs 3.)

Pretty much every shortest path algorithm is built on this rule. What changes between them is which edges they relax, and in what order. Dijkstra picks them very carefully, using the heap. Bellman-Ford doesn't pick at all.

Bellman-Ford

def bellman_ford(graph, start):
    dist = {node: float('inf') for node in graph}
    dist[start] = 0.0

    # Relax every edge, up to n - 1 times
    for _ in range(len(graph) - 1):
        updated = False
        for u in graph:
            for v, w in graph[u]:
                if dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
                    updated = True
        if not updated:
            break

    return dist

print(bellman_ford(graph, 'A'))
# {'A': 0.0, 'B': 3.0, 'C': 2.0, 'D': 8.0, 'E': 10.0, 'F': 13.0}

The first thing you'd notice if you open them side by side is the missing heapq import. Bellman-Ford doesn't prioritise anything: it relaxes every edge, in rounds, up to n−1n - 1 times5, and stops early if a whole round changes nothing. That's O(nm)O(nm), much slower than Dijkstra. It's usually taught because it handles negative edges, which Dijkstra can't6, but BMSSP only works with non-negative weights, so that's not why we need it here.

We need it for this property: after ii rounds, every node whose shortest path has at most ii edges already has its correct distance. Bellman-Ford finishes nodes by number of hops, not by distance, and it doesn't need to sort anything to do it.

The work can also be cut short in two ways: run only kk rounds instead of n−1n - 1, or ignore any distance above some cap BB. BMSSP does both, and the next post in the series was going to start there, with a bounded version of Dijkstra.

Corrections (November 2026): the September version had a few mistakes, now fixed. The Bellman-Ford example used negative edges that formed a negative cycle, so its "shortest" distance wasn't defined; it now uses the same graph as the Dijkstra example. The Dijkstra code returned a single distance instead of all of them. Edge relaxation was explained as "the direct path is never longer than a detour", which is backwards, and the sorting barrier was misstated. Footnotes 4 and 6 and the hop-count property of Bellman-Ford are new.

Update, November 2026

The series stopped there: I never wrote the bounded-Dijkstra post. I came back to it in November 2026, and everything below was written then, with the help of AI for structuring and formatting. By then other people had implemented BMSSP too, so this part also covers what they found.

Spoiler: my simplified Python version is slower than Dijkstra, and so is every other implementation I found, including a full one in C++. I also found out the hard way that the paper's assumption that all path lengths are different matters: skipping it gave me wrong answers, and then an infinite loop.

How BMSSP works

BMSSP uses both algorithms, but bounded, with the two knobs from above:

They're easy to mix up: kk counts edges, and BB caps distances. Bounding the work like this lets BMSSP split the problem into small pieces and never sort all the nodes at once.

Dijkstra's problem is the frontier: every node goes through one big heap, and every extract-min costs log⁡n\log n. BMSSP keeps the frontier small, and splits the work by distance. Its recursive function solves a "bounded multi-source" problem, hence the name: given a set of frontier nodes SS and a cap BB, find the true distance of every node closer than BB whose shortest path goes through SS. The top-level call is S={s}S = \{s\} and B=∞B = \infty, which is just regular single-source shortest paths.

Each call does four things:

  1. Shrink the frontier (FindPivots). Run kk rounds of Bellman-Ford from SS, capped at BB. Everything within kk hops of SS is now done. Then look at the shortest-path trees hanging from each node in SS: a tree with fewer than kk nodes is already finished. Only the roots of big trees stay. Those are the pivots, and there are about kk times fewer of them than nodes Bellman-Ford touched.
  2. Split by distance and recurse. Put the pivots into a priority structure DD. Pull out the closest ones, along with a bound BiB_i that separates them from the rest, and recurse one level down with cap BiB_i. Relax the edges of the nodes the sub-call finished: anything that lands in [Bi,B)[B_i, B) goes back into DD for later. Repeat until DD is empty.
  3. Base case. At the bottom, there's a single source. Run a small Dijkstra from it, and stop after k+1k + 1 nodes.
  4. Stop early. Each level has a budget of nodes. When a call fills it, it stops and reports how far it got, and the caller picks up from there.

Very roughly, instead of one big sort over all nn nodes, BMSSP does many small sorts over frontiers that FindPivots keeps shrinking, and the paper's special data structure for DD makes those small sorts cheap. That's intuition, not a proof. The proof is sections 3 and 4 of the paper, and it's dense.

My Python implementation

My implementation (linked at the end) is about 200 lines of Python, and it simplifies the paper in two big ways:

  1. A plain heap instead of the paper's data structure DD (Lemma 3.3). Same interface, worse complexity. This is the big one: without it, we don't get the paper's bound. It's still correct.
  2. No constant-degree transformation. The paper rewrites the graph so every node has at most two incoming and two outgoing edges. That matters for the analysis, not for correctness.

I tested it the simple way: run Dijkstra and BMSSP on the same graph and compare every distance. I ran it on 3,000 random directed graphs with 1 to 4,096 nodes and either real-valued or small integer weights, plus 2,000 graphs where most or all edges weigh zero, and every distance matched. That doesn't prove it's correct: random graphs won't catch a bug that only shows up on some structure they don't produce.

Getting there took two bug fixes, and both were about ties.

Two tie-breaking bugs

The paper assumes that all path lengths are different, and handles ties by comparing paths as tuples, not just their lengths. It's easy to skip, so I did. The first version compared plain distances, and it passed every test with random real-valued weights (where ties basically never happen). With small integer weights it got wrong answers on 68 out of 200 graphs.

The suspect is pull, the operation that takes the closest nodes out of DD. It has to return a bound that's strictly above every node it pulled and at or below every node it left. With ties, two nodes at the same distance can end up on opposite sides of the bound. Comparing (distance, node id) instead of distances gives every node a unique key, and that fixed all 200 graphs.

That fix wasn't enough. On graphs with zero-weight edges, BMSSP didn't give wrong answers: it never finished. Take a zero-weight edge from node 7 to node 1. Both end up at the same distance, and node 1 gets the smaller key, even though it comes after 7 on the path. The base case starts from 7, finds 1, and returns the largest key it saw as the new bound. That's 7's own key, so 7 isn't "done" and goes back on the frontier. Then it gets pulled again, and the same thing happens, forever.

The algorithm relies on following an edge always giving a bigger key. Positive weights guarantee that, but zero weights don't (the paper's whole-path comparison does). Adding the hop count in the middle is enough to get it back, because a zero-weight edge adds nothing to the distance, but it always adds one hop:

def key(self, v):
    """Order vertices by (distance, hops, id) so no two keys are ever equal."""
    return (self.dist[v], self.hops[v], v)

Castro, Clementino and de Freitas, who implemented the full algorithm in C++ (more on that below), use the same kind of key: length, then hop count, then vertex, then predecessor7. The paper's authors also start their 2026 follow-up (below) by defining a tie-breaking rule for distance labels. BMSSPy uses (length, path size, edge id), and its paper gives the original paper's own key as (length, path size, u, v): the hop count was in the paper all along, and it's exactly the part I skipped.

Is it faster?

No. On random sparse graphs (average degree 4), my version is about 3× slower than Dijkstra at 100K and 1M nodes (16 s against 5.5 s at a million, on an M1 Pro), and it does 2–3× more edge relaxations. Most of the extra relaxations come from FindPivots' Bellman-Ford rounds and from the recursion relaxing the same edges again at each level.

In hindsight, that's the result to expect, for two reasons. First, my version has no DD, so every frontier operation still costs log⁡n\log n, like in Dijkstra, and BMSSP does more of them. It tests the algorithm's structure and its correctness, not the theorem. Second, the theoretical win is small: compared to Dijkstra with a binary heap, it's a factor of log⁡1/3n\log^{1/3} n, about 2.7 for a million nodes, and BMSSP's overhead easily costs more than that. Even the parameter kk that controls how much FindPivots shrinks the frontier is stuck at 2 until n=227n = 2^{27}, about 134 million nodes.

Better evidence comes from people who went further than I did:

My 3× in Python is in line with these results, including the complete C++ implementation. BMSSP shows that shortest paths don't have to pay for sorting, at least in theory. In practice, on any graph you're likely to run, Dijkstra with a binary heap is still faster.

The theory kept moving, though. In February 2026, Duan, Mao, Shu and Yin published a faster algorithm, O(mlog⁡nlog⁡log⁡n)O(m\sqrt{\log n \log\log n}) on sparse graphs (ICALP 2026). It builds on the same BMSSP recursion and makes finding pivots cheaper. I haven't tried implementing it.

Links

Footnotes

  1. Negative edges break Dijkstra's core assumption: once a node is finished, its distance can't improve. ↩︎

  2. With the lazy approach, the heap can hold up to mm entries, but log⁡m≤log⁡n2=2log⁡n\log m \le \log n^2 = 2 \log n, so it's still O(mlog⁡n)O(m \log n). A plain array instead of a heap gives O(n2)O(n^2), which is actually better for dense graphs, where m≈n2m \approx n^2. ↩︎

  3. Rarely worth it because: 1. a binary heap is simpler and has better cache locality, 2. Fibonacci heaps have large constant factors (they can be 20-30× slower on small inputs), and 3. most real-world graphs are sparse. ↩︎

  4. If you do want the nodes in order, Dijkstra is about as good as it gets: Haeupler, Hladík, Rozhoň, Tarjan and Tětek showed that Dijkstra, with the right kind of heap, is universally optimal for that problem. ↩︎

  5. Any shortest path, in a graph without negative cycles, has at most n−1n - 1 edges. ↩︎

  6. Bellman-Ford can also detect negative cycles: if a round after the (n−1)(n-1)-th still updates something, there's a cycle with negative total weight, and "shortest distance" stops making sense (you can loop forever and keep getting shorter). ↩︎

  7. Their paper doesn't mention zero-weight edges, so I can't tell whether they hit the same loop. BMSSPy, which Castro co-wrote, does have to handle them (its constant-degree transformation adds zero-weight cycles), and its key includes the path size too. ↩︎