Part 17 / Topic 18 of 20
Shortest paths (Dijkstra)
BFS finds the path with the fewest EDGES. The moment edges carry weights — kilometres, rupees, minutes — fewest edges can be the wrong answer. Dijkstra's algorithm fixes that: keep a min-heap of (cost so far, node), always extend the cheapest unfinished route, and the first time the goal is popped, that cost is the smallest possible. O((V + E) log V) with the heap doing the "cheapest next" work. Think of water flooding a network of pipes from the start: it reaches every junction in order of total distance travelled, not in order of pipe count — Dijkstra is that flood, run on a heap.
| Algorithm | Finds | Needs |
|---|---|---|
| BFS | fewest edges/hops | unweighted edges |
Dijkstra (heapq) |
smallest total weight | nonnegative weights |
The same road map, two honest answers (full graph in the example file):
BFS, fewest hops: Pune -> Delhi (1 hop)
Dijkstra, fewest km: Pune -> Nashik -> Indore -> Delhi (1360 km)
Pune has a direct 1,500 km highway to Delhi — one hop, but 140 km longer than the three-hop route. The heart of the algorithm:
def shortest_by_distance(start, goal):
heap = [(0, start, [start])]
best_distance = {start: 0}
while heap:
distance, city, path = heapq.heappop(heap) # cheapest route so far
if city == goal:
return distance, path
for neighbour, road_distance in ROADS.get(city, []):
new_distance = distance + road_distance
if neighbour not in best_distance or new_distance < best_distance[neighbour]:
best_distance[neighbour] = new_distance
heapq.heappush(heap, (new_distance, neighbour, path + [neighbour]))
return None
Real-world example: a delivery app answers "fewest tolls" with BFS on toll-free hops but "fastest route" with Dijkstra over minutes — same map, different weights, different algorithm.
⚠️ Dijkstra requires nonnegative weights. Popping a node assumes no later route can undercut it; one negative edge breaks that promise and silently returns wrong answers. Negative weights need Bellman–Ford (see the advanced extensions below).
Practice: cheapest route in a weighted graph (fares, minutes, effort); grid versions where each cell has a cost; "minimize the maximum edge on the path" variants, which swap the sum for a max but keep the heap.
Practice on LeetCode - start here: Network Delay Time · Path With Minimum Effort · Cheapest Flights Within K Stops
Show the full practice list (3 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Path with Maximum Probability | Medium |
| Min Cost to Connect All Points | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Swim in Rising Water | Hard |
Full program: examples/18_shortest_paths.py.
Exercise 18: Shortest paths — cheapest metro route
Scenario: Metro fares differ per hop; the cheapest route from one station to another is not always the one with the fewest changes.
What to do: Write cheapest_route(start, goal) with Dijkstra: a min-heap of (cost_so_far, station, path), a best dict of the cheapest cost seen per station, and return (cost, path) the first time goal is popped (or None if it never is). Print the cheapest Vanaz → Ramwadi route and an unreachable check.
Starting data:
FARES = {
"Vanaz": [("Garware", 10), ("Deccan", 25)],
"Garware": [("Vanaz", 10), ("Deccan", 10)],
"Deccan": [("Garware", 10), ("Vanaz", 25), ("Budhwar Peth", 15)],
"Budhwar Peth": [("Deccan", 15), ("Ramwadi", 30)],
"Ramwadi": [("Budhwar Peth", 30)],
}
Sample output:
Cheapest Vanaz -> Ramwadi: Rs 65 via Vanaz -> Garware -> Deccan -> Budhwar Peth -> Ramwadi
Unreachable check: None
Show the solution to Exercise 18
"""Exercise 18: Shortest paths - cheapest metro route.
Dijkstra with a min-heap of (cost_so_far, station, path): the cheapest
unfinished route is always extended first, so the first pop of the
goal station is the cheapest way to reach it. Fares are nonnegative,
which is exactly what Dijkstra requires.
Run: python ex18.py (macOS/Linux: python3 ex18.py)
"""
import heapq
FARES = {
"Vanaz": [("Garware", 10), ("Deccan", 25)],
"Garware": [("Vanaz", 10), ("Deccan", 10)],
"Deccan": [("Garware", 10), ("Vanaz", 25), ("Budhwar Peth", 15)],
"Budhwar Peth": [("Deccan", 15), ("Ramwadi", 30)],
"Ramwadi": [("Budhwar Peth", 30)],
}
def cheapest_route(start: str, goal: str) -> tuple[int, list[str]] | None:
heap = [(0, start, [start])]
best: dict[str, int] = {start: 0}
while heap:
cost, station, path = heapq.heappop(heap)
if station == goal:
return cost, path
for neighbour, fare in FARES.get(station, []):
new_cost = cost + fare
if neighbour not in best or new_cost < best[neighbour]:
best[neighbour] = new_cost
heapq.heappush(heap, (new_cost, neighbour, path + [neighbour]))
return None
def main() -> None:
cost, path = cheapest_route("Vanaz", "Ramwadi")
print(f"Cheapest Vanaz -> Ramwadi: Rs {cost} via {' -> '.join(path)}")
print(f"Unreachable check: {cheapest_route('Ramwadi', 'Nowhere')}")
if __name__ == "__main__":
main()