Shortest paths: Dijkstra on weighted graphs
When edges have costs, BFS isn't enough. Dijkstra's algorithm with a priority queue, why it works, and when you need something else.
In short
Dijkstra is BFS with a priority queue keyed by distance so far. Always expand the closest unfinished node; its distance is then final. It needs non-negative weights. Cost: O((V + E) log V).
Greedy, one node at a time
Pop the closest node from the heap, then relax each edge: if going through this node gives a shorter distance to a neighbour, update it and push it. Watch A → C → B beat the direct edge.
priority queue (distance, node)
1def dijkstra(graph, src):2 dist = {src: 0}3 heap = [(0, src)]4 while heap:5 d, node = heapq.heappop(heap)6 if d > dist.get(node, inf): continue7 for nb, w in graph[node]:8 nd = d + w9 if nd < dist.get(nb, inf):10 dist[nb] = nd11 heapq.heappush(heap, (nd, nb))12 return dist
Variables
Why it works, and when it doesn't
When a node is popped, every other unfinished node is at least as far away. With non-negative weights no later route through them can be shorter, so the popped distance is final. A negative edge breaks that argument.
| Situation | Algorithm | Cost |
|---|---|---|
| Unweighted (all edges cost 1) | BFS | O(V + E) |
| Weights ≥ 0 | Dijkstra | O((V + E) log V) |
| Negative weights, detect negative cycles | Bellman-Ford | O(V·E) |
| All pairs of nodes | Floyd-Warshall | O(V³) |
| Weights are only 0 or 1 | 0-1 BFS (a deque) | O(V + E) |
Key takeaways
- 01Dijkstra = BFS with a min-heap keyed by distance.
- 02A popped node's distance is final (needs non-negative weights).
- 03Relax edges: update when dist[node] + w < dist[neighbour].
- 04Negative weights → Bellman-Ford.
Check your understanding
1 of 3
What data structure drives Dijkstra's algorithm?
Related topics
BFS & DFS
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
10 min read →Priority queues
A heap keeps the smallest (min-heap) or largest (max-heap) item at the root, and every parent is ≤ its children. Reading the top is O(1); push and pop are O(log n). It's the data structure behind a priority queue.
8 min read →