impera Open Impera

A levels Computer Science · Algorithms

Dijkstra's shortest path

1The shortest path problem

Given a weighted graph, find the route between two vertices with the lowest total weight (distance, time or cost). This is the problem sat-navs and network routers solve.

Dijkstra's algorithm finds the shortest path from one start vertex to every other vertex, as long as no edge has a negative weight.

Check yourself

What kind of graph does Dijkstra's algorithm work on?

  • A weighted graph with no negative edge weights

  • Only trees

  • Only unweighted graphs

  • Any graph, including negative weights

Show the answer

A weighted graph with no negative edge weights

Non-negative weights.

2The algorithm

  1. Give the start vertex a distance of 0 and every other vertex infinity.
  2. Pick the unvisited vertex with the smallest distance and mark it visited.
  3. For each unvisited neighbour, calculate distance via this vertex. If it is smaller than the neighbour's current distance, update it and record this vertex as its previous vertex.
  4. Repeat steps 2 and 3 until every vertex is visited (or the target is visited).
  5. Follow the previous vertices back from the target to get the route.

Once a vertex is visited, its distance is final: no shorter route to it can be found later.

Check yourself

Which vertex is visited next in Dijkstra's algorithm?

  • The unvisited vertex with the smallest current distance

  • The next unvisited vertex in alphabetical order

  • The unvisited vertex furthest from the start

  • The unvisited vertex with the most edges connected to it

Show the answer

The unvisited vertex with the smallest current distance

Greedy choice.

3A worked trace

Final shortest distances from A. The red edges form the shortest-path tree; note that B is reached more cheaply through C (3) than directly (4).

Worked example

Dijkstra from A

  1. Start: A = 0, the rest ∞. Visit A: C = 2, B = 4.
  2. Smallest unvisited is C (2). Visit C: B via C = 2 + 1 = 3 < 4, so B = 3 (previous C). D via C = 2 + 8 = 10.
  3. Visit B (3): D via B = 3 + 5 = 8 < 10, so D = 8 (previous B).
  4. Visit D (8): E = 8 + 3 = 11.
  5. Visit E (11). Route to E: E ← D ← B ← C ← A, so A → C → B → D → E, length 11.
StepABCDEVisited
1042∞∞A
203210∞A, C
30328∞A, C, B
4032811A, C, B, D
Check yourself

In the trace, why does B's distance change from 4 to 3?

  • The route A → C → B (2 + 1) is shorter than the direct edge (4)

  • B was visited twice, so its distance was recalculated

  • Dijkstra always reduces distances by 1 on each pass

  • The weight of edge AB changed during the algorithm

Show the answer

The route A → C → B (2 + 1) is shorter than the direct edge (4)

Relaxing the edge.

4Implementing with a priority queue

A priority queue keeps the unvisited vertices ordered by distance, so the smallest is always removed first.

import heapq
def dijkstra(graph, start):
    dist = {v: float("inf") for v in graph}
    dist[start] = 0
    pq = [(0, start)]
    while pq:
        d, v = heapq.heappop(pq)
        if d > dist[v]:
            continue                      # an old, longer entry
        for n, w in graph[v]:
            if d + w < dist[n]:
                dist[n] = d + w
                heapq.heappush(pq, (dist[n], n))
    return dist

With a priority queue (a binary heap), Dijkstra runs in O((V + E) log V). With a simple list, finding the smallest each time makes it O(V²).

Check yourself

What does the priority queue do in Dijkstra's algorithm?

  • Reverses the route at the end so it reads from the start

  • Stores the edges in alphabetical order for quick lookup

  • Always gives the unvisited vertex with the smallest distance

  • Removes any negative weights before the search begins

Show the answer

Always gives the unvisited vertex with the smallest distance

Smallest first.

5The A* algorithm

A* is a faster version for finding a route to one target. It adds a heuristic h(v), an estimate of the distance left (for example the straight-line distance on a map):

$$f(v) = g(v) + h(v)$$

where g(v) is the distance so far. A* visits the vertex with the smallest f, so it heads towards the target instead of spreading out in every direction.

  • If the heuristic never overestimates the real distance, A* still finds the shortest path.
  • A* is used in games (route-finding for characters) and sat-navs.
Check yourself

What does the heuristic in A* estimate?

  • The distance already travelled from the start

  • The remaining distance from a vertex to the target

  • The largest edge weight anywhere in the graph

  • The number of edges left before the target

Show the answer

The remaining distance from a vertex to the target

Guess of what is left.

6Uses and limits

Uses of shortest-path algorithms:

  • sat-nav and map route planning;
  • network routing protocols (such as OSPF) that send data packets along the cheapest path;
  • planning delivery routes and flight connections.

Limits:

  • Dijkstra gives wrong answers if edges have negative weights.
  • On huge graphs, such as a whole country's roads, it may be too slow without a heuristic (A*) or pre-processing.
Check yourself

Why can Dijkstra fail with negative edge weights?

  • Negative numbers cannot be stored in the distance table used by the algorithm

  • It loops forever in every case, because distances keep getting smaller each time

  • The priority queue breaks when a negative value is added, so the program crashes

  • A visited vertex's distance is treated as final, but a negative edge could make it shorter later

Show the answer

A visited vertex's distance is treated as final, but a negative edge could make it shorter later

Final too early.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera