---
title: Dijkstra Algorithm in Python: Explained with heapq Code
url: https://www.masaischool.com/resources/dijkstra-algorithm-explained
description: Dijkstra's shortest path algorithm in Python with heapq, a worked weighted graph, why negative weights break it, and a table against BFS, Bellman-Ford and A*.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Dijkstra's Algorithm in Python: Shortest Path with a Heap, and When It Fails

> **Short answer**
>
> Dijkstra's algorithm finds the cheapest path from one source node to every other node in a graph whose edge weights are not negative. It keeps a min-heap of (distance, node) pairs, always settles the closest unsettled node, and relaxes its edges. With a binary heap it runs in O((V + E) log V) time.

This page is for students who know BFS and want the weighted version. It assumes you can read an adjacency list; if not, start with the [graph data structure page](https://www.masaischool.com/resources/graph-data-structure-explained) and [BFS vs DFS](https://www.masaischool.com/resources/bfs-vs-dfs-explained).

The code was run with Python 3 on 1 December 2026, and the output shown is the real output. The complexity figures are standard results for the algorithms named, not measurements.

1. **Set distances** - Source 0, others infinity
2. **Push source** - Heap holds (0, source)
3. **Pop the smallest** - Skip stale entries
4. **Relax each edge** - Push any improvement
5. **Repeat until empty** - Distances are final
The loop of Dijkstra's algorithm.

## How Dijkstra's algorithm works

Dijkstra's algorithm answers one question: what is the cheapest route from a source node to every other node, when each edge has a non-negative cost? It keeps a best-known distance for each node, starts them at infinity except the source at 0, and repeatedly takes the unsettled node with the smallest distance.

That node is now final. The reason is the whole point of the algorithm: every other unsettled node is at least as far, and no edge is negative, so no later route can reach this node more cheaply. For each outgoing edge, the algorithm checks whether going through this node improves the neighbour's distance. This check is called **relaxing** the edge.

A min-heap makes the "smallest unsettled node" step fast. Python's heapq has no decrease-key operation, so the standard trick is to push a new pair on every improvement and ignore stale pairs when they surface. The [heapq documentation](https://docs.python.org/3/library/heapq.html) describes this approach under priority queue implementation notes. See also the [heap data structure page](https://www.masaischool.com/resources/heap-data-structure-explained).

## Python implementation with heapq

The graph below has five nodes. Each entry is a pair of (neighbour, weight). The cheapest route from A to E is not the fewest-edge route, which is what makes it a good test: A to B to E has only two edges but costs 9.import heapq graph = { "A": [("B", 4), ("C", 1)], "B": [("E", 5)], "C": [("B", 2), ("D", 5)], "D": [("E", 1)], "E": [], } def dijkstra(graph, source): dist = {node: float("inf") for node in graph} parent = {source: None} dist[source] = 0 heap = [(0, source)] while heap: d, node = heapq.heappop(heap) if d > dist[node]: continue # stale entry: a shorter route was already found for nxt, w in graph[node]: nd = d + w if nd < dist[nxt]: dist[nxt] = nd parent[nxt] = node heapq.heappush(heap, (nd, nxt)) return dist, parent def path_to(parent, target): path = [] while target is not None: path.append(target) target = parent[target] return path[::-1] dist, parent = dijkstra(graph, "A") print(dist) print("A to E:", " -> ".join(path_to(parent, "E")), "cost", dist["E"])

The printed distances are A 0, B 3, C 1, D 6, E 7. B is reached through C at cost 1 + 2 = 3, not directly at cost 4. The route to E is A, C, D, E, with cost 1 + 5 + 1 = 7. The alternative A to C to B to E costs 8, and A to B to E costs 9.

### The run by hand

Start with A at 0 and the heap holding (0, A). Pop A: relax B to 4 and C to 1, push both. Pop (1, C): B improves to 3 and D becomes 6, push both. Pop (3, B): E becomes 8. Pop (4, B): stale, skipped. Pop (6, D): E improves from 8 to 7. Pop (7, E) and (8, E): the second is stale. The heap is empty, so the distances are final. Writing this table on paper once is the fastest way to remember the loop.

### What the line if d > dist[node]: continue does

A node can be pushed more than once. B is pushed with distance 4 when A is processed, and again with distance 3 when C is processed. The 4 entry stays in the heap. When it is finally popped, dist[B] is already 3, so 4 > 3 and the entry is skipped. Without this line the code is still correct but does extra work.

### Complexity

Each edge can cause at most one push, so the heap holds at most E entries and each push or pop costs O(log E), which is O(log V) since E is at most V squared. Total time is O((V + E) log V), space is O(V + E). An array-based version without a heap is O(V squared), which can beat the heap version on very dense graphs.

## Why negative weights break Dijkstra

The correctness argument above fails the moment one edge is negative: a node settled early could still be reached more cheaply later, through a path that goes up first and then down. In the graph below, A to B costs 2 directly. But A to C costs 3 and C to B costs minus 5, so the true cheapest route to B costs minus 2.import heapq # One edge is negative: C -> B costs -5 graph = { "A": [("B", 2), ("C", 3)], "B": [], "C": [("B", -5)], } def dijkstra(graph, source): dist = {n: float("inf") for n in graph} dist[source] = 0 done = set() heap = [(0, source)] while heap: d, node = heapq.heappop(heap) if node in done: continue done.add(node) # Dijkstra treats this distance as final for nxt, w in graph[node]: if d + w < dist[nxt] and nxt not in done: dist[nxt] = d + w heapq.heappush(heap, (d + w, nxt)) return dist def bellman_ford(graph, source): dist = {n: float("inf") for n in graph} dist[source] = 0 for _ in range(len(graph) - 1): for u in graph: for v, w in graph[u]: if dist[u] + w < dist[v]: dist[v] = dist[u] + w for u in graph: # one more pass: any change means a negative cycle for v, w in graph[u]: if dist[u] + w < dist[v]: raise ValueError("negative cycle") return dist print("Dijkstra :", dijkstra(graph, "A")) print("Bellman-Ford:", bellman_ford(graph, "A"))

Dijkstra reports B as 2 because it settled B before it ever looked at C's edge. Bellman-Ford reports the correct minus 2. Bellman-Ford relaxes every edge V - 1 times, so it does not depend on settling order, and one extra pass can detect a negative cycle (a loop whose total weight is negative, where no cheapest path exists).

Some Dijkstra variants re-push a node when its distance improves after settling. They can return right answers on small negative-edge graphs but lose the time bound and can take exponential time in the worst case, so do not rely on them. If a problem has negative weights, reach for Bellman-Ford. If it has none, use Dijkstra.

## Dijkstra vs BFS, Bellman-Ford, Floyd-Warshall and A*

With every weight equal to 1, Dijkstra and BFS give identical distances. The last block checks that on a small graph; it prints True followed by the distance dictionary.from collections import deque import heapq # Same shape as an unweighted graph: BFS and Dijkstra with all weights 1 agree edges = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": []} def bfs_dist(g, s): dist = {s: 0} q = deque([s]) while q: u = q.popleft() for v in g[u]: if v not in dist: dist[v] = dist[u] + 1 q.append(v) return dist def dijkstra_dist(g, s): dist = {s: 0} h = [(0, s)] while h: d, u = heapq.heappop(h) if d > dist[u]: continue for v in g[u]: if d + 1 < dist.get(v, float("inf")): dist[v] = d + 1 heapq.heappush(h, (d + 1, v)) return dist print(bfs_dist(edges, "A") == dijkstra_dist(edges, "A"), bfs_dist(edges, "A"))

| Algorithm | Solves | Negative weights | Time | Use it when |
|---|---|---|---|---|
| BFS | Single source, unweighted | Not applicable | O(V + E) | All edges cost the same, or you count hops |
| Dijkstra | Single source, weighted | No | O((V + E) log V) with a binary heap | Non-negative costs: roads, network latency, game maps |
| Bellman-Ford | Single source, weighted | Yes, and detects negative cycles | O(V times E) | Negative edges, or you must detect a negative cycle |
| Floyd-Warshall | All pairs of nodes | Yes, no negative cycles | O(V cubed) | Small graphs where you need every pair at once |
| A* (A-star) | Single source to one goal | No | Depends on the heuristic | Pathfinding with a distance estimate, such as grids and maps |

A* is named here only for context: it is Dijkstra with an extra estimate of the remaining distance to the goal, which lets it ignore regions that look unpromising. It is rarely asked in written interviews. The usual question set is BFS, Dijkstra and sometimes Bellman-Ford.

In practice, link-state routing protocols such as OSPF use Dijkstra-style shortest-path calculation, and map software uses variants of it. For other uses of graph algorithms see [applications of graphs](https://www.masaischool.com/resources/applications-of-graph-in-data-structure).

## Practice: problems that use Dijkstra

- LeetCode 743, Network Delay Time: single-source shortest path, then take the maximum distance. The plainest Dijkstra practice.
- Shortest path on a grid with different cell costs: treat each cell as a node and use the same heap loop.
- Cheapest route with at most k stops: needs a modified state (node, stops used), which is where plain Dijkstra stops being enough.
- Compare with BFS first: solve a maze with BFS, then add costs per cell and see exactly which line has to change.

Time yourself: writing Dijkstra from a blank file, with the stale-entry check, should take under ten minutes once practised. The [coding practice websites](https://www.masaischool.com/resources/tools/coding-practice-websites) list has places to find these problems, and the [competitive programming roadmap](https://www.masaischool.com/resources/competitive-programming-roadmap) places shortest paths in month four.

## Frequently asked questions

### What is Dijkstra's algorithm used for?

It finds the shortest or cheapest path from one source to all other nodes in a graph with non-negative edge weights. Typical uses are route finding on road networks, network routing, and games or robotics where moving between cells has different costs. It is also a common interview and exam topic.

### What is the time complexity of Dijkstra's algorithm?

With a binary heap and an adjacency list it is O((V + E) log V), where V is the number of nodes and E the number of edges. With a plain array instead of a heap it is O(V squared), which can be better on very dense graphs. Space is O(V + E).

### Why does Dijkstra not work with negative weights?

It assumes that once a node has the smallest known distance, no later path can beat it. A negative edge breaks that, because a longer-looking route can become cheaper after a negative edge is added. The code in this page returns 2 for a node whose true cheapest cost is minus 2.

### What is the difference between Dijkstra and Bellman-Ford?

Dijkstra is faster, O((V + E) log V), but needs non-negative weights. Bellman-Ford is slower, O(V times E), but handles negative edges and can detect negative cycles. Pick Dijkstra when weights are costs like distance or time, and Bellman-Ford when edges can represent gains or refunds.

### Is Dijkstra a greedy algorithm?

Yes. At each step it commits to the unsettled node with the smallest distance and never revisits that choice. The greedy choice is safe only because edge weights are non-negative, which is the same condition under which the algorithm is correct.

### How do I get the actual path and not just the distance?

Store a parent for each node whenever you improve its distance, then walk back from the target to the source and reverse the list. The code above does this with the parent dictionary and a small helper, and prints A, C, D, E as the route to E.
