Algorithms · Level 3 Graphs

Dijkstra's Shortest Path

Find the cheapest delivery route on a road map with Dijkstra's algorithm and a heap, where counting roads instead of costs picks the wrong route.

  • always expand the cheapest place
  • a heap of (cost, place)
  • fewest roads is not cheapest

Dijkstra's algorithm always expands the cheapest place reached so far, using a heap of (cost, place). When a place comes off the heap, its cost is final (costs are never negative). Trap: counting roads, as BFS does, isn't counting cost; two cheap roads can beat one expensive one.

import heapq
heap = [(0, "depot")]
heapq.heappush(heap, (7, "b"))
heapq.heappush(heap, (3, "a"))
heapq.heappop(heap)  # (0, 'depot')
heapq.heappop(heap)  # (3, 'a'): cheapest next

Write cheapest_route(roads, start, end): roads is a list of two-way (a, b, cost) roads. Return the lowest total cost from start to end, or -1 if end can't be reached. Example: cheapest_route([('A', 'B', 5), ('A', 'C', 1), ('C', 'B', 2)], 'A', 'B') → 3.

solution.py
Test Suites Pending
Output