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
- Give the start distance 0 and every other vertex distance ∞ (unknown).
- Pick the unfinished vertex with the smallest distance. Its distance is now final.
- Relax its edges: for each neighbour, if going through this vertex is shorter than the neighbour's current distance, update it.
- 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.
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?
| Situation | Use | Time |
|---|---|---|
| No weights (every edge counts 1) | BFS | O(V + E) |
| Weights 0 or 1 only | 0-1 BFS (a deque) | O(V + E) |
| Positive weights, one start | Dijkstra | O((V + E) log V) |
| Some negative weights, one start | Bellman-Ford (relax every edge V − 1 times; can also spot negative cycles) | O(V × E) |
| Shortest path between every pair, small graph | Floyd-Warshall (try every vertex as a middle stop) | O(V³) |
| Directed graph with no cycles (DAG) | Relax edges in topological order | O(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
Quiz score: 0 of 3
Exercises solved: 0 of 1
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.