Skip to content
Visual explainer 3h 30m to learn 4 steps

Dijkstra's algorithm

Find single-source shortest paths with non-negative weights using a heap.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 36 of 54

In short

Dijkstra's algorithm finds the shortest distance from a source to every vertex when all edge weights are non-negative. It always expands the closest unfinished vertex, taken from a min-heap, and relaxes its outgoing edges. It is the core of route planning and network routing protocols such as OSPF.

Explained simply

Think of a map app. Roads connect places, and each road has a length or a travel time. You want the quickest way from your home to every other place. Dijkstra's algorithm (say "DYKE-stra") solves exactly this, as long as no road has a negative length.

The idea is simple. Keep a best-known distance for every place. Start with 0 for home and infinity for the rest. Then, again and again, pick the closest place you have not finished yet. Its distance can no longer get better, so you lock it in.

From that locked place, look at each road leaving it. If going through it gives a shorter trip to a neighbour, write down the new, smaller distance. This step is called relaxing an edge. An edge is one road in the graph, and its weight is its length.

To find the closest unfinished place quickly, we use a min-heap (a priority queue that always gives back the smallest item). In Python that is the heapq module. With it, Dijkstra handles graphs with millions of edges in seconds.

Press Play on a diagram to walk through it one step at a time.

CycleDijkstra main loop
  1. 1
    Pop closest

    Smallest (dist, u) from the heap.

  2. 2
    Skip stale

    If dist is worse than best[u].

  3. 3
    Relax edges

    best[u] + w < best[v]?

  4. 4
    Push update

    Push (new dist, v).

  5. Back to step 1
FlowTrace: A to B 4, A to C 1, C to B 2, B to D 1, C to D 5
  1. 1
    Pop (0, A)

    Push (4, B) and (1, C).

  2. 2
    Pop (1, C)

    B improves to 3, D set to 6; push both.

  3. 3
    Pop (3, B)

    D improves to 4; push (4, D).

  4. 4
    Pop (4, B)

    Stale: 4 > 3, skip.

  5. 5
    Pop (4, D)

    D is final at 4.

  6. 6
    Result

    A 0, C 1, B 3, D 4.

MapWhich shortest-path tool fits?
Edge weights
  • All equal
    • BFS, O(V + E)
  • Only 0 or 1
    • 0-1 BFS with a deque, O(V + E)
  • Non-negative
    • Dijkstra, O((V + E) log V)
  • Some negative
    • Bellman-Ford, O(V x E)
  • Graph is a DAG
    • Relax in topological order, O(V + E)

In depth

Why the closest vertex is safe to lock in

When Dijkstra pops vertex u with distance d, every other unfinished vertex has a distance of at least d. Any other route to u must leave the finished area through one of those vertices, so it already costs at least d before it even reaches u. With non-negative weights, the rest of that route can only add length, never remove it. So d is final.

This argument is the whole reason for the "non-negative" rule. One negative edge lets a long detour suddenly become cheaper, and a vertex you already locked could improve later. Dijkstra never looks back, so it would keep the wrong answer.

  • Finished vertices come out of the heap in order of distance
  • Each vertex is finalised exactly once
  • Zero-weight edges are fine; negative ones are not

Lazy deletion and the real cost

A textbook priority queue has a decrease-key operation to lower a vertex's priority in place. Python's heapq does not. Instead we push a new (distance, vertex) pair every time a distance improves, and when an old pair is popped later we notice it is stale (its distance is bigger than the best one) and skip it.

Each successful relaxation pushes one entry, so the heap holds at most E entries in total, where E is the number of edges. Every push and pop costs O(log E). Since E is at most V^2, log E is at most 2 log V, so the total is O((V + E) log V), the same bound as the decrease-key version.

For very dense graphs (E close to V^2), a version without a heap that scans an array for the closest vertex runs in O(V^2), which is better than O(V^2 log V).

FlowLife of one heap entry
  1. 1
    Push (5, B)

    First route to B found, cost 5.

  2. 2
    Push (3, B)

    A cheaper route appears; best[B] = 3.

  3. 3
    Pop (3, B)

    Smaller pair comes out first; B is final.

  4. 4
    Pop (5, B)

    5 > best[B], so it is stale.

  5. 5
    Skip

    No edges are relaxed for it.

Rebuilding the route and stopping early

Distances alone rarely satisfy a user; they want the route. Keep a parent dictionary. Whenever you relax edge u to v, set parent[v] = u. At the end, walk from the target back through parents to the source and reverse the list.

If you only need one target, you can stop the moment that target is popped from the heap. Its distance is final by the argument above, and any work after that point is wasted. On a road network this often cuts the search to a small circle around the source.

  • parent[v] = u on every successful relaxation
  • Walk back from the target, then reverse
  • Unreachable targets never get a parent

Variants you will meet

Many problems are Dijkstra in disguise. A grid where each cell has a cost is a graph with up to 4 edges per cell. Several starting points? Push all of them with distance 0 at the start (multi-source Dijkstra). Extra rules, such as "you may use one free ticket", become extra fields in the state: the vertex becomes (place, ticket_used), and the graph doubles in size.

When every weight is 0 or 1, use 0-1 BFS instead: a deque where 0-weight edges go to the front and 1-weight edges to the back. It runs in O(V + E). When all weights are equal, plain BFS is enough. A* search is Dijkstra plus a guess of the remaining distance, which helps it head towards the target.

Learn it in 4 short steps

About 55m each. Track them with a timer in your plan.

  1. 1
    Relax edges and track distances~55m
  2. 2
    Implement Dijkstra with heapq~55m
  3. 3
    Skip stale heap entries~55m
  4. 4
    Explain why negative weights break it~55m

Key points

  • Time O((V + E) log V) with a binary heap.
  • Fails with negative edge weights because finalised distances could later improve.
  • Lazy deletion: push duplicates and skip stale entries when popped.
  • Stop early when the target is popped if you only need one distance.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
import heapq

def dijkstra(adj, src):           # adj[u] = [(v, w), ...]
    dist = {src: 0}
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist.get(u, float('inf')):
            continue                  # stale
        for v, w in adj[u]:
            nd = d + w
            if nd < dist.get(v, float('inf')):
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist

Shortest route with the actual path

We use the graph from the trace diagram and want the route from A to D. Step 1: run Dijkstra and record parent[v] each time a distance improves. Step 2: stop when D is popped, because its distance is final. Step 3: walk back D, B, C, A through the parents and reverse. The answer is cost 4 via A, C, B, D. Note that the direct-looking route A, C, D costs 6 and loses.

python
import heapq
adj = {"A": [("B", 4), ("C", 1)], "C": [("B", 2), ("D", 5)], "B": [("D", 1)]}
def route(src, dst):
    dist, parent, heap = {src: 0}, {src: None}, [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if u == dst: break               # first pop of dst is final
        if d > dist[u]: continue         # stale entry
        for v, w in adj.get(u, []):
            if d + w < dist.get(v, float("inf")):
                dist[v], parent[v] = d + w, u; heapq.heappush(heap, (d + w, v))
    path, node = [], dst
    while node is not None: path.append(node); node = parent[node]
    return dist[dst], path[::-1]
print(route("A", "D"))  # (4, ['A', 'C', 'B', 'D'])

Network delay time

A signal starts at node k and travels along directed cables, each with a delay. How long until every node has the signal? That is the largest shortest distance from k. If some node is never reached, the answer is -1. This version finalises a node the first time it is popped and ignores later pops, which is another common way to handle stale entries. For times [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2: nodes 1 and 3 get the signal at time 1, node 4 at time 2, so the answer is 2.

python
import heapq
from collections import defaultdict

def network_delay(times, n, k):
    adj = defaultdict(list)
    for u, v, w in times: adj[u].append((v, w))
    dist, heap = {}, [(0, k)]
    while heap:
        d, u = heapq.heappop(heap)
        if u in dist: continue          # already final
        dist[u] = d
        for v, w in adj[u]:
            if v not in dist: heapq.heappush(heap, (d + w, v))
    return max(dist.values()) if len(dist) == n else -1

print(network_delay([[2, 1, 1], [2, 3, 1], [3, 4, 1]], 4, 2))  # 2

Quick reference

  • Binary-heap Dijkstra: O((V + E) log V) time, O(V + E) space
  • Lazy deletion: the heap holds at most E entries; skip a pop when d > dist[u]
  • The first time the target is popped, its distance is final, so you can stop
  • Dense graph (E near V^2): the array version without a heap is O(V^2)
  • Weights only 0 or 1: 0-1 BFS with a deque, O(V + E)
  • Equal weights: plain BFS; any negative weight: Bellman-Ford
  • Store parent[v] = u when relaxing to rebuild the path
  • Extra rules (stops, tickets, keys) become extra fields in the state tuple

Common mistakes

  • Running Dijkstra on graphs with negative weights.
  • Forgetting to skip stale heap entries, wasting time.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Edges: A to B weight 4, A to C weight 1, C to B weight 2. What is the shortest distance from A to B?

Question 2

2With lazy deletion in heapq, what is the most entries the heap can ever hold, roughly?

Question 3

3Edges: A to B weight 2, A to C weight 3, C to B weight -2. What does Dijkstra report for B?

Question 4

4All edge weights are either 0 or 1. Which approach is asymptotically fastest?

Question 5

5Why can't you fix negative weights by adding the same constant to every edge?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Using the dijkstra function from the explainer (dist is a dict), write within(adj, src, limit) that returns how many vertices, including src, are at distance at most limit.

  2. Exercise 2medium

    A grid holds a cost in each cell. You start at the top-left, pay for every cell you enter (including the start), and may move up, down, left or right. Return the minimum total cost to reach the bottom-right.

  3. Exercise 3hard

    You may make exactly one edge free (cost 0) on your trip. Find the cheapest cost from src to dst. adj maps u to a list of (v, w).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does Dijkstra work on undirected graphs?
Yes. Add every undirected edge in both directions to the adjacency list. The weights must still be non-negative.
Why not just use BFS for shortest paths?
BFS finds the path with the fewest edges, which is the shortest only when every edge has the same weight. With different weights, a path with more but cheaper edges can win.
What is the difference between Dijkstra and A*?
A* is Dijkstra that orders the heap by distance so far plus an estimate of the distance left. If the estimate never overestimates, A* still finds a shortest path and usually explores far fewer vertices.
Can Dijkstra handle a graph with a zero-weight cycle?
Yes. Zero weights are non-negative, so the proof still holds; a zero cycle never makes any distance smaller.

Go deeper

ShareXLinkedInWhatsApp