Dijkstra's Algorithm: Shortest Paths with Non-Negative Weights
Breadth-first search finds shortest paths when every edge counts the same. Once edges have lengths (road distances, travel times, costs), the path with the fewest edges is often not the cheapest, and you need a different algorithm. For graphs whose edge weights are all non-negative, the standard choice is Dijkstra's algorithm. It solves the single-source shortest paths problem: the distance from one source vertex to every other vertex.
The condition is not a detail. With even one negative edge, Dijkstra's algorithm can return a wrong distance without any warning, and this guide shows a three-vertex example where it does. Examples use Python 3.10 or later and only the standard library.
The greedy idea
Dijkstra's algorithm keeps a tentative distance for every vertex: 0 for the source and infinity for the rest. It also keeps a set of finished vertices whose distances are final. Each step does two things:
- Pick the unfinished vertex u with the smallest tentative distance, and mark it finished.
- Relax each edge u to v with weight w: if dist[u] + w is smaller than dist[v], lower dist[v] and remember u as v's parent.
Why is it safe to finish u at step 1? Every other route to u has to leave the finished set at some unfinished vertex x, and x's tentative distance is already at least dist[u], because u was the smallest. The rest of that route adds edge weights, and if no weight is negative the total can only stay the same or grow. So nothing found later can beat dist[u]. This is a greedy algorithm: it commits to the choice that looks cheapest right now and never revisits it, and the argument above is what makes that choice correct.
A heapq implementation
Finding the smallest tentative distance quickly is what a priority queue is for, and Python's heapq module provides a binary min-heap (see heaps and priority queues). heapq has no "decrease key" operation, so the code uses lazy deletion: when a distance improves, it pushes a new entry and leaves the old one in the heap. When an old entry is popped later, the vertex is already finished and the entry is skipped.
The graph is an adjacency list mapping each vertex to a list of (neighbor, weight) pairs. The program runs two graphs: a small positive example, and a graph with one negative edge, discussed below.
import heapq
def dijkstra(graph, source):
dist = {source: 0}
parent = {source: None}
done = set()
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if u in done:
continue # stale entry: lazy deletion
done.add(u) # u's distance is now final
for v, w in graph[u]:
if v in done:
continue
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
parent[v] = u
heapq.heappush(heap, (nd, v))
return dist, parent
def path_to(parent, target):
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
graph = {
"S": [("A", 4), ("B", 1)],
"A": [("C", 1)],
"B": [("A", 2), ("C", 5)],
"C": [("D", 3)],
"D": [],
}
dist, parent = dijkstra(graph, "S")
print(dist)
print(path_to(parent, "D"))
# One negative edge: C -> B has weight -2.
negative = {
"A": [("B", 2), ("C", 3)],
"B": [],
"C": [("B", -2)],
}
dist, parent = dijkstra(negative, "A")
print(dict(sorted(dist.items())))
{'S': 0, 'A': 3, 'B': 1, 'C': 4, 'D': 7}
['S', 'B', 'A', 'C', 'D']
{'A': 0, 'B': 2, 'C': 3}
Trace the first graph. S is popped at 0 and sets A to 4 and B to 1. B is popped at 1 and improves A to 1 + 2 = 3 (going through B beats the direct edge of weight 4) and sets C to 6. A is popped at 3 and improves C to 4. The stale entries (4, A) and (6, C) are skipped when they come out. C is popped at 4 and sets D to 7. The path to D, rebuilt by following parents back from D, is S, B, A, C, D, with total weight 1 + 2 + 1 + 3 = 7.
If you need only one target, you can stop as soon as the target is popped: its distance is final at that moment.
Running time
Each vertex is finished once, and each edge is relaxed at most once (when its source is finished). Every successful relaxation pushes one heap entry, so the heap holds at most E + 1 entries, and each push or pop costs O(log E). Because E is at most V^2, log E is at most 2 log V, so that is O(log V). The total is:
- O((V + E) log V) time with a binary heap and an adjacency list, and O(V + E) space.
- O(V^2) time with no heap at all: keep distances in an array and find the minimum by scanning all V entries, V times. This is better for dense graphs, where E is close to V^2 and the heap version would cost O(V^2 log V).
For sparse graphs, where E is a small multiple of V, the heap version wins clearly. More advanced heaps improve the theoretical bound to O(E + V log V), but a binary heap is what you will use in practice. The graph representations guide explains why an adjacency list is the natural input here.
What goes wrong with a negative edge
The second graph in the program has three edges: A to B with weight 2, A to C with weight 3, and C to B with weight -2. The true shortest distance to B is 1, along A, C, B (3 + (-2) = 1). Dijkstra's algorithm returns {'A': 0, 'B': 2, 'C': 3}.
Here is what happened. A is popped and sets B to 2 and C to 3. B is now the closest unfinished vertex, so it is popped and finished at 2. Then C is popped at 3, and the edge C to B gives 3 + (-2) = 1. But B is already finished, so the textbook algorithm does not touch it. The safety argument failed at exactly one point: it assumed the rest of a route can only add non-negative weight, and the edge of weight -2 broke that.
Nothing in the output signals a problem. That is why the requirement belongs in your head before you choose the algorithm, not in a test afterward.
Some heap-based versions drop the finished set and allow a vertex to be improved and pushed again after it was popped. On this small graph such a version happens to reach the right answer. It is no longer Dijkstra's algorithm in the sense that matters, though: the O((V + E) log V) guarantee is gone, some graphs make it do far more work, and if a negative cycle is reachable it never stops. The rule is simple: if any edge weight can be negative, use Bellman-Ford. On this graph Bellman-Ford returns {'A': 0, 'B': 1, 'C': 3}, and it also detects negative cycles; see Bellman-Ford and negative edge weights.
Adding a constant to every weight to make them all positive does not fix the problem either. It penalizes paths with more edges more heavily, so it changes which path is shortest.
Common mistakes
- Skipping the stale-entry check. Without
if u in done: continue, a vertex popped a second time rescans all of its edges with an outdated, larger distance. With non-negative weights those relaxations never succeed, so the answer stays correct, but the work grows with every stale entry. - Using it on unweighted graphs. It works, but BFS gives the same answer in O(V + E).
- Undirected graphs stored one way. For an undirected road, add the edge to both vertices' lists.
- Unreachable vertices. They never appear in
dist. Decide whether your caller expects them missing or at infinity.
History
Edsger W. Dijkstra designed the algorithm in 1956 and published it in 1959 in "A note on two problems in connexion with graphs" (Numerische Mathematik, volume 1). The same short paper also gives a method for the minimum spanning tree problem.
Check yourself
- All weights are 1. What does Dijkstra's algorithm compute, and what is a faster way to get it? (Distances by edge count; BFS.)
- A graph has V = 1000 and E = 400,000. Heap or array? (E is a large fraction of V^2 = 1,000,000, so the graph is dense, and the O(V^2) array version is the better fit.)
- Why is B wrong in the negative example, while C is right? (B was finished before the negative edge into it was seen; nothing negative leads into C.)