bmssp series 1 - dijkstra
A few weeks ago, I read an interesting paper titled "Breaking the Sorting Barrier for Directed Single-Source Shortest Paths". Shortest path algorithms are widely used for GPS applications, networking, game AIs... finding the shortest path saves time and resources, and this new algorithm can potentially make things even more efficient for large graphs.
I wanted to write about it and implement it, but soon realized there's a few pre-requisites for understanding the paper and its implementation, and covering all in one post would be too much. Therefore, this is the first post of a (short) series on graph theory algorithms, going from Dijkstra to BMSSP ("Bounded Multi-Source Shortest Path"). BMSSP is based on Dijkstra, one of the simplest path-finding algorithms, so it makes sense to start there.
I'll cover Dijkstra by going through the theory briefly, and implementing a simple version without path recall (still works for finding the shortest path).
By definition, Dijkstra is an algorithm to find single-source () shortest paths in a graph with non-negative weighted edges1, i.e. the shortest path from one node to every other node. It keeps a queue of unvisited nodes, a set of visited nodes to avoid repetition, and a map of distances from to any other node.
How does this look in a minimal implementation? First, the data structures needed:
pq = [(0.0, start)]
visited = set()
dist = {node: float('inf') for node in graph}
dist[start] = 0.0
- The unvisited set is a priority queue
pqimplemented as a min-heap (heapqin python). visitedis aset.- The distance array is a dictionary, with all distances initialized to except for , set to .
Some implementations add a predecessor array . It's not really needed for computing shortest distances, but it can be used to reconstruct paths, updated whenever a shorter path to a node is found. We're skipping for this implementation.
while pq:
d, u = heapq.heappop(pq)
if u in visited:
continue
visited.add(u)
if u == end:
return dist[end]
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[end]
This loop is called the "extract min" loop. It's the main iterative step where the algorithm repeatedly extracts the node with the smallest current distance estimate from the priority queue (or min-heap). This extracted node is considered to have its shortest path finalized from the source. The algorithm then relaxes the edges2 adjacent to this node, updating the distances of its neighbors if shorter paths are found. This loop continues until the priority queue (or min-heap) is empty, meaning all nodes have been processed.
So for an undirected graph like the one below
\usepackage{tikz-cd}
\begin{document}
\begin{tikzcd}[every cell/.append style={nodes={circle,draw=gray,minimum size=2em}}, row sep=2em, column sep=3em]
A \arrow[r, "2" description, no head] \arrow[d, "4" description, no head] & C \arrow[d, "8" description, no head] \arrow[r, "10" description, no head] & E \arrow[d, "3" description, no head] \\
B \arrow[r, "5" description, no head] \arrow[ru, "1" description, no head] & D \arrow[r, "6" description, no head] \arrow[ru, "2" description, no head] & F
\end{tikzcd}
\end{document}
It would look like:
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')]
Distances: {'A': 0, 'B': 4, 'C': 2, 'D': inf, 'E': inf, 'F': inf}
Iteration 2: Visiting C (distance: 2)
Relaxed: B(3), D(10), E(12)
Queue: [(3, 'B'), (4, 'B'), (10, 'D'), (12, 'E')]
Distances: {'A': 0, 'B': 3, 'C': 2, 'D': 10, 'E': 12, 'F': inf}
Iteration 3: Visiting B (distance: 3)
Relaxed: D(8)
Queue: [(4, 'B'), (8, 'D'), (10, 'D'), (12, 'E')]
Distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 12, 'F': inf}
Iteration 4: Visiting D (distance: 8)
Relaxed: E(10), F(14)
Queue: [(10, 'D'), (10, 'E'), (12, 'E'), (14, 'F')]
Distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 14}
Iteration 5: Visiting E (distance: 10)
Relaxed: F(13)
Queue: [(12, 'E'), (13, 'F'), (14, 'F')]
Distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}
Iteration 6: Visiting F (distance: 13)
Processing vertices in distance order using a binary heap as a priority queue sets a sorting lower bound of : each vertex is extracted once (), and each edge causes at most one decrease-key operation ()). That's already better than using an array/list (naive implementation), with 3, but worse than using a Fibonacci heap, with (this is usually not worth it.4)
That part from sorting the nodes becomes a massive bottleneck on huge graphs.
In the next posts, we'll go through a few iterations from Dijkstra to BMSSP, finding suboptimal solutions and implementing a few improvements detailed in the paper. These iterations will aim to improve the complexity until we reach the target of set by BMSSP.
Here's the full code for this minimal example:
import heapq
def dijkstra_minimal(graph, start, end):
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)
if u == end:
return dist[end]
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[end]
# Example usage
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_minimal(graph, 'A', 'F')) # Output: 13
Negative edges break the algorithm's core assumption that once a node is visited, we've found its shortest path.↩
Relaxation means updating a node's distance if we find a shorter path through the current node.↩
Array implementation beats heap for dense graphs where though.↩
Rarely worth it because 1. binary heap is simpler and has better cache locality, 2. Fibonacci heap has large constant factors (can be 20-30x slower on small inputs), and 3. most real-world graphs are sparse ().↩