When every edge has a cost.
Use a priority queue for nonnegative weighted paths and ignore stale entries.
01 Model 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.
A settled minimum distance cannot be improved by a later nonnegative route.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
START source distance at zero
POP the smallest tentative distance
SKIP outdated entries
RELAX outgoing nonnegative edges03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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
- 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 Count the cost
O((V + E) log V) on simple graphs with a binary heap
O(V + E), including stale heap entries
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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"])06 Check your reasoning
What edge-cost restriction does Dijkstra need?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.