Module 9 · Graphs and Tries · Lesson 31 of 40

Shortest paths with weights: Dijkstra

Find the cheapest route when edges have different costs, with a heap. Plus when to use Bellman-Ford and Floyd-Warshall.

In this lesson · about 24 minutes

  • Explain Dijkstra's algorithm in plain words
  • Implement it with heapq
  • Pick the right shortest-path method for a problem

BFS counts edges. But if one road is 2 km and another is 50 km, the path with fewer roads may not be the shortest. For weighted graphs we need something smarter.

Dijkstra's algorithm

  1. Give the start distance 0 and every other vertex distance ∞ (unknown).
  2. Pick the unfinished vertex with the smallest distance. Its distance is now final.
  3. Relax its edges: for each neighbour, if going through this vertex is shorter than the neighbour's current distance, update it.
  4. Repeat until every vertex is finished.

Why does step 2 work? All edge weights are positive, so no later detour can make the closest vertex any closer.

A min-heap picks the closest vertex fast. With a heap, Dijkstra runs in O((V + E) log V).

Try it · see it work

Dijkstra's shortest paths from A

The orange numbers are road lengths; the blue numbers under each city are the best distance so far from A.

4125810263A0B∞C∞D∞E∞F∞

Step 1 of 8Start at A with distance 0. Every other distance starts as ∞ (unknown).

Try it: Dijkstra with heapq

Exercise

Cheapest route

Finish cheapest(graph, start, goal) using Dijkstra. Return the smallest total cost from start to goal, or -1 if it can't be reached.

Code that runs before yours
import heapq
flights = {
    "Addis": [("Nairobi", 200), ("Cairo", 300)],
    "Nairobi": [("Cairo", 50), ("Lagos", 400)],
    "Cairo": [("Lagos", 250)],
    "Lagos": [],
    "Accra": [],
}

Which shortest-path method?

SituationUseTime
No weights (every edge counts 1)BFSO(V + E)
Weights 0 or 1 only0-1 BFS (a deque)O(V + E)
Positive weights, one startDijkstraO((V + E) log V)
Some negative weights, one startBellman-Ford (relax every edge V − 1 times; can also spot negative cycles)O(V × E)
Shortest path between every pair, small graphFloyd-Warshall (try every vertex as a middle stop)O(V³)
Directed graph with no cycles (DAG)Relax edges in topological orderO(V + E)

Why Dijkstra fails with negative weights: it marks a vertex "final" too early. A negative edge found later could make it cheaper, but Dijkstra never looks back.

Check your understanding0 of 3 correct

Question 1

1.Which vertex does Dijkstra finish next?

Question 2

2.A graph has negative edge weights. Which method is safe?

Question 3

3.What does 'relax an edge' mean?

Quiz score: 0 of 3

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.