Home / Learn / Dijkstra’s algorithm step by step
Learn

Dijkstra’s algorithm step by step

Settle the closest node, then relax its neighbours.

The idea

Dijkstra’s algorithm finds the shortest distance from one start node to every other node in a graph whose edge weights are not negative. Exam questions give you an edge list and ask for the shortest path length, or for the order nodes are settled.

The method

  1. Give the start node distance 0 and every other node ∞.
  2. Repeatedly pick the unsettled node with the smallest known distance and settle it. Its distance is now final.
  3. For each neighbour, check whether going through the settled node is shorter. If so, update it.
  4. Stop when every node you care about is settled.

Worked example

Edges: A–B (4), A–C (2), C–B (1), B–D (5), C–D (8), D–E (3). What is the shortest distance from A to E?

StepSettleABCDE
1A (0)042∞∞
2C (2)03210∞
3B (3)0328∞
4D (8)032811
5E (11)032811

Settle order: A, C, B, D, E. The best route is A → C → B → D → E.

Answer: 2 + 1 + 5 + 3 = 11

Common mistakes

  • Stopping when you first see the target instead of when you settle it.
  • Forgetting that a longer-looking path can be cheaper (A→C→B beats A→B here).
  • Using Dijkstra with negative weights, where it can give wrong answers.

Practise this topic

Try questions on this topic with instant explanations, or test yourself against the world in the ranked exam.