When every edge has a cost.
Use a priority queue for nonnegative weighted paths and ignore stale entries.
01 The idea
Dijkstra’s algorithm repeatedly settles the smallest tentative distance. It works when edge costs are nonnegative. A min-heap prioritises the next candidate, and a distance map stores the best cost found so far. This implementation pushes improved distances rather than modifying heap entries in place; outdated entries are skipped when popped.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import heapq
def distances(graph, start):
best, queue = {start: 0}, [(0, start)]
while queue:
cost, node = heapq.heappop(queue)
if cost != best[node]: continue
for neighbour, weight in graph.get(node, []):
if weight < 0: raise ValueError("Nonnegative weights required")
candidate = cost + weight
if candidate < best.get(neighbour, float("inf")):
best[neighbour] = candidate
heapq.heappush(queue, (candidate, neighbour))
return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
print(distances(graph, "A")["B"])3
03 Under the hood
- 1
A→C→B costs three, improving on the direct edge cost four. The priority queue explores candidates by total cost, not edge count.
- 2
An older candidate for B can remain in the heap after a better route is found. The stale-entry check prevents redundant processing.
- 3
This fixture uses comparable string vertex names, so equal heap costs can compare the second tuple element. Arbitrary vertex objects need a counter tie-breaker. Validate all reachable edge weights and choose a different algorithm if negatives are allowed.
04 Your turn, builder
Compare the cost of a direct route with an indirect cheaper route in a small nonnegative graph.
Reveal one possible solution +
import heapq
def distances(graph, start):
best, queue = {start: 0}, [(0, start)]
while queue:
cost, node = heapq.heappop(queue)
if cost != best[node]: continue
for neighbour, weight in graph.get(node, []):
if weight < 0: raise ValueError("Nonnegative weights required")
candidate = cost + weight
if candidate < best.get(neighbour, float("inf")):
best[neighbour] = candidate
heapq.heappush(queue, (candidate, neighbour))
return best
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": []}
result = distances(graph, "A")
assert result["B"] == 3
print("Direct: 4; best route:", result["B"])05 Check your signal
What edge-cost restriction does Dijkstra need?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.