Dijkstra's Shortest Paths

Find the cheapest route to every node in a weighted graph, always expanding the closest node next with a heap.

Python · intermediate · 10 min · 58 steps · free

What you'll learn

dijkstra.py

import heapq

graph = {'A': {'B': 4, 'C': 1}, 'B': {'D': 1}, 'C': {'B': 2, 'D': 5}, 'D': {}}

def dijkstra(start):
    dist = {start: 0}
    heap = [(0, start)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue
        for neighbor, weight in graph[node].items():
            new = d + weight
            if new < dist.get(neighbor, float('inf')):
                dist[neighbor] = new
                heapq.heappush(heap, (new, neighbor))
    return dist

print(dijkstra('A'))

Step by step

  1. This brings in Python's built-in heapq module, so the program can use the functions it provides.
  2. A weighted graph: A → B costs 4, A → C costs 1, and so on.
  3. Python defines the function dijkstra(). Its body does not run yet: it runs each time the function is called.
  4. Python calls dijkstra(), with start = 'A'. It gets its own names.
  5. dist is created and points to a new dict: {A: 0}.
  6. heap is created and points to a new list: [a tuple].
  7. heap is true, so the loop body runs.
  8. d is created with the value 0. node is created with the value 'A'. a tuple is removed from the end of the list that heap points to.
  9. d > dist[node] is false, so the block under it is skipped.
  10. neighbor is created with the value 'B'. weight is created with the value 4.
  11. new is created with the value 4.
  12. new < dist.get(neighbor, float('inf')) is true, so the block under it runs.
  13. A new key B with the value 4 is added to the dict that dist points to.
  14. a tuple is added to the end of the list that heap points to.
  15. neighbor changes from 'B' to 'C'. weight changes from 4 to 1.
  16. new changes from 4 to 1.
  17. new < dist.get(neighbor, float('inf')) is true, so the block under it runs.
  18. A new key C with the value 1 is added to the dict that dist points to.
  19. In the list that heap points to, index 0 changes from a tuple to a tuple and index 1 changes from null to a tuple.
  20. Python moves to the next item of the loop: for neighbor, weight in graph[node].items().
  21. heap is true, so the loop body runs.
  22. The heap hands back the closest unfinished node: C, at distance 1.
  23. d > dist[node] is false, so the block under it is skipped.
  24. neighbor changes from 'C' to 'B'. weight changes from 1 to 2.
  25. new changes from 1 to 3.
  26. new < dist.get(neighbor, float('inf')) is true, so the block under it runs.
  27. Going A → C → B costs 1 + 2 = 3, cheaper than the direct 4: update B.
  28. In the list that heap points to, index 0 changes from a tuple to a tuple and index 1 changes from null to a tuple.
  29. neighbor changes from 'B' to 'D'. weight changes from 2 to 5.
  30. new changes from 3 to 6.
  31. new < dist.get(neighbor, float('inf')) is true, so the block under it runs.
  32. A new key D with the value 6 is added to the dict that dist points to.
  33. a tuple is added to the end of the list that heap points to.
  34. Python moves to the next item of the loop: for neighbor, weight in graph[node].items().
  35. heap is true, so the loop body runs.
  36. d changes from 1 to 3. node changes from 'C' to 'B'. a tuple is removed from the start of the list that heap points to.
  37. d > dist[node] is false, so the block under it is skipped.
  38. weight changes from 5 to 1.
  39. new changes from 6 to 4.
  40. new < dist.get(neighbor, float('inf')) is true, so the block under it runs.
  41. D in the dict that dist points to changes from 6 to 4.
  42. a tuple is added to the end of the list that heap points to.
  43. Python moves to the next item of the loop: for neighbor, weight in graph[node].items().
  44. heap is true, so the loop body runs.
  45. d changes from 3 to 4. In the list that heap points to, index 0 changes from a tuple to a tuple.
  46. d > dist[node] is true, so the block under it runs.
  47. This (4, "B") entry is out of date: B is already known at 3. Skip it.
  48. heap is true, so the loop body runs.
  49. node changes from 'B' to 'D'. a tuple is removed from the start of the list that heap points to.
  50. d > dist[node] is false, so the block under it is skipped.
  51. Python moves to the next item of the loop: for neighbor, weight in graph[node].items().
  52. heap is true, so the loop body runs.
  53. d changes from 4 to 6. a tuple is removed from the end of the list that heap points to.
  54. d > dist[node] is true, so the block under it runs.
  55. Line runs: continue.
  56. heap is false, so the loop ends.
  57. Shortest distances from A: B 3, C 1, D 4.
  58. dijkstra() has finished, so its names are gone. It prints {'A': 0, 'B': 3, 'C': 1, 'D': 4}.

Common mistakes

Best practices

Key takeaways

Check yourself

Why skip when d > dist[node]?

Answer: That entry is outdated

Negative weights?

Answer: Use Bellman-Ford instead

·

More in Graphs