Dijkstra's shortest path, visually
Sunil Tiwari · Oct 12, 2026 · 6 min read
Dijkstra's algorithm on a small weighted graph: intuition, code, complexity and a worked trace.
Dijkstra's algorithm answers a simple question: starting from one node, what is the cheapest way to reach every other node? It works on any graph whose edge weights are non-negative, and it powers everything from map routing to network protocols like OSPF.
This page walks through it on a six-node graph. The canvas next to it shows the same graph, the loop, and every step of the trace.
The idea in one sentence
Always settle the closest node you have not settled yet. Nothing found later can beat its distance, because every other route already costs at least as much.
That is the whole algorithm. Everything else is bookkeeping: a table of best-known distances and a priority queue that hands you the closest candidate.
The example graph
Six nodes, nine directed edges, all weights positive. We start at A.
| Edge | Weight | Edge | Weight | Edge | Weight |
| A → B | 4 | B → D | 5 | D → E | 2 |
| A → C | 2 | C → D | 8 | D → F | 6 |
| C → B | 1 | C → E | 4 | E → F | 3 |
Here is the answer, drawn as the shortest-path tree. Green edges sit on a cheapest path, grey dashed edges were tried and lost.

Relaxation: the only operation
Dijkstra improves distances with one move. For an edge u→v with weight w(u,v), relaxing it means:
In words: "if going through u is cheaper than the best route to v I know, remember the new route." Every distance starts at ∞ except the source, which starts at 0.
Three kinds of nodes
At any moment each node belongs to exactly one set:
- Settled: its distance is final.
- Frontier: we have found some route to it, and it is waiting in the heap.
- Unseen: no route found yet, so its distance is still ∞.
Each round moves the cheapest frontier node into the settled set and relaxes its outgoing edges, which can pull unseen nodes into the frontier or lower the distance of frontier nodes. Here is the picture after A and C are settled:

Notice that B already improved from 4 (directly from A) to 3 (through C). That is relaxation doing its job.
The loop

The version below uses Python's heapq. Instead of a "decrease key" operation, which binary heaps do not offer, it pushes a fresh entry whenever a distance improves and ignores outdated entries when they surface. This "lazy deletion" is the standard way to write Dijkstra in practice.
import heapq
def dijkstra(graph, source):
"""graph: {node: [(neighbour, weight), ...]}"""
dist = {node: float("inf") for node in graph}
dist[source] = 0
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry: u was already settled cheaper
for v, w in graph[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("D", 5)],
"C": [("B", 1), ("D", 8), ("E", 4)],
"D": [("E", 2), ("F", 6)],
"E": [("F", 3)],
"F": [],
}
print(dijkstra(graph, "A"))
# {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 6, 'F': 9}To recover the actual paths, keep a prev[v] = u map and update it whenever a relaxation succeeds. Walking prev backwards from any node gives its route.
Worked trace from A
- Settle A (0). Relax: B = 4, C = 2.
- Settle C (2). Relax: B = min(4, 2 + 1) = 3, D = 2 + 8 = 10, E = 2 + 4 = 6.
- Settle B (3). Relax: D = min(10, 3 + 5) = 8.
- Pop the old entry (4, B). It is stale, so skip it.
- Settle E (6). Relax: F = 6 + 3 = 9.
- Settle D (8). Relax: E would be 10 (worse than 6), F would be 14 (worse than 9). Nothing changes.
- Settle F (9). The last entry, (10, D), is stale. The heap is empty, so we are done.
Final distances: A 0 · B 3 · C 2 · D 8 · E 6 · F 9.
Here is the same trace from the heap's point of view. Every push and every pop, including the stale ones:

Two things are worth noticing. Nodes are settled in order of distance (0, 2, 3, 6, 8, 9), never out of order. And D is settled after E even though D was discovered first, because what matters is cost, not discovery time.
Why it is correct
When a node u is popped with distance d, every node still in the frontier has a tentative distance of at least d. Any other route to u must leave the settled set through some frontier node, which already costs at least d, and then add edges of non-negative weight. So no other route can be cheaper than d.
That argument breaks the moment an edge weight is negative: a long detour could end with a negative edge that undercuts a node you already settled.
Complexity
With a binary heap, each edge can trigger at most one push, and each push or pop costs O(logV) (the heap holds at most E entries, and logE≤2logV):
| Priority queue | Time | When it wins |
| Plain array scan | O(V2) | Dense graphs, where E≈V2 |
| Binary heap | O((V+E)logV) | Almost everything in practice |
| Fibonacci heap | O(E+VlogV) | Theory, very large dense graphs |
Memory is O(V+E) for the graph, the distance table and the heap.
Choosing the right algorithm
Dijkstra is the default for single-source shortest paths with non-negative weights, but it is not always the best tool:

- BFS is Dijkstra with every weight equal to 1, and a plain queue replaces the heap.
- Bellman-Ford handles negative weights and detects negative cycles, at O(VE).
- Floyd-Warshall gives the distance between every pair of nodes in O(V3).
- A* is Dijkstra with a heuristic that pulls the search toward one goal. With a heuristic that never overestimates, it still finds the optimal path and usually explores far fewer nodes.
Common mistakes
- Negative weights. Dijkstra can return wrong answers silently. Use Bellman-Ford instead.
- Forgetting the stale check. Without
if d > dist[u]: continue, old entries re-relax edges and the running time can blow up on dense graphs. - Marking nodes visited on push instead of pop. A node's distance is only final when it leaves the heap. Marking it earlier locks in a route that may not be the cheapest (B in our trace would be stuck at 4).
- Stopping too late for a single target. If you only need the route to one node, you can stop as soon as that node is popped.