Algorithms Playbook
PatternTime O((V + E) log V) · Space O(V)9 min read

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.

Dijkstra: shortest paths from A
Speed

priority queue (distance, node)

0A:0
4215810263Ad = 0Bd = ∞Cd = ∞Dd = ∞Ed = ∞Fd = ∞
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): continue
7 for nb, w in graph[node]:
8 nd = d + w
9 if nd < dist.get(nb, inf):
10 dist[nb] = nd
11 heapq.heappush(heap, (nd, nb))
12 return dist
Shortest paths from A in a weighted graph. Distance to A is 0 and everything else is unknown (∞). The priority queue always gives the closest unfinished node.

Variables

srcA
Step 1/21· Pops: 0
Dijkstra needs non-negative weights. It's BFS where the queue is replaced by a priority queue ordered by distance so far.

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.

SituationAlgorithmCost
Unweighted (all edges cost 1)BFSO(V + E)
Weights ≥ 0DijkstraO((V + E) log V)
Negative weights, detect negative cyclesBellman-FordO(V·E)
All pairs of nodesFloyd-WarshallO(V³)
Weights are only 0 or 10-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