Dijkstra's algorithm (shortest path)

Computer Science · Algorithms

Question 1 of 10

0

    What does Dijkstra’s algorithm find?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Dijkstra's algorithm (shortest path) explained

    Dijkstra's algorithm finds the shortest route from one node to every other node in a weighted graph, where each edge has a cost such as distance or time. It is used in satellite navigation and in the routing of data across networks.

    The algorithm keeps a record of the best known distance to each node. It starts with 0 for the start node and infinity for the rest. At each step it picks the unvisited node with the smallest recorded distance, marks it as finished, and checks each of its neighbours.

    1. Set the start node's distance to 0 and all other distances to ∞\infty.
    2. Choose the unvisited node with the smallest distance and mark it as visited.
    3. For each unvisited neighbour, add the edge cost to the current distance. If the total is less than the neighbour's recorded distance, replace the recorded distance.
    4. Repeat until every node is visited.

    Dijkstra's algorithm only works when no edge costs are negative. A common mistake is to take the first route found instead of the cheapest one, when the recorded distances should be compared before choosing.

    Worked example

    Find the shortest distance from A to C. The direct edge A to C costs 7. The route A to B costs 3, and the edge B to C costs 2.

    1. Visit A. Set B to 0+3=30 + 3 = 3 and C to 0+7=70 + 7 = 7.
    2. Visit B, which has the smallest distance, 3. Going through B gives C the distance 3+2=53 + 2 = 5. Since 5<75 < 7, C is updated to 5.
    3. Visit C with distance 5. There are no shorter routes.

    The shortest distance from A to C is 5, via B.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does Dijkstra’s algorithm find?

      • The shortest path in a weighted graph
      • The longest path
      • Any path
      • The largest cycle
    • Medium

      A weighted undirected graph has these edges (weight in brackets): A–B (8), B–C (1), C–D (5), A–D (3). Using Dijkstra’s algorithm, what is the shortest distance from A to D?

    • Hard

      A weighted undirected graph has these edges (weight in brackets): A–B (9), B–C (6), C–D (1), D–E (6), B–E (6), B–D (3). Using Dijkstra’s algorithm, what is the shortest distance from A to E?