Graphs and shortest paths · Algorithm 9 of 15
Dijkstra’s Algorithm
Find minimum-weight paths when every edge weight is non-negative. Citation needed
The whole, before the parts
Dijkstra’s algorithm finds the shortest distances from one starting point in a network whose connection costs are non-negative. A route map illustrates the goal: compare total route costs, not just the number of connections. Citation needed
Terminology and core concepts
Relaxing an edge means checking whether reaching its destination through the current vertex improves the best known distance. Dijkstra’s algorithm always processes the smallest tentative distance next. A min-priority queue, implemented here as a heap, makes that choice efficient. With non-negative weights, no route through a more distant unfinished vertex can improve the distance being finalized. This example returns distances, not reconstructed routes. Citation needed
Learning path
Trace an example
edges: A-B 1, A-C 4, B-C 2, B-D 6, C-D 3 (directed) process best distances after relaxation A (0) A:0 B:1 C:4 B (1) A:0 B:1 C:3 D:7 C (3) A:0 B:1 C:3 D:6 C (4) stale entry: skip D (6) shortest distance to D finalized D (7) stale entry: skip
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
from heapq import heappush, heappop
from itertools import count
def dijkstra(graph, start):
if any(w < 0 for edges in graph.values() for _, w in edges):
raise ValueError('Dijkstra requires non-negative weights')
distance = {start: 0}
serial = count()
heap = [(0, next(serial), start)]
while heap:
cost, _, vertex = heappop(heap)
if cost != distance[vertex]:
continue
for neighbor, weight in graph.get(vertex, []):
candidate = cost + weight
if candidate < distance.get(neighbor, float('inf')):
distance[neighbor] = candidate
heappush(heap, (candidate, next(serial), neighbor))
return distance
graph = {'A': [('B', 1), ('C', 4)], 'B': [('C', 2), ('D', 6)],
'C': [('D', 3)], 'D': []}
assert dijkstra(graph, 'A') == {'A': 0, 'B': 1, 'C': 3, 'D': 6}
assert dijkstra({}, 'A') == {'A': 0}Citation needed
Analyze the cost
This lazy heap implementation may store O(E) queued entries. Including validation of all edges, time is O(V + E log(E + 1)) and extra space is O(V + E). On simple graphs, this is commonly written O((V + E) log V). Unreachable vertices are omitted. We assume finite numeric weights and expected constant-time dictionary operations. Citation needed
A mistake to watch for
Negative weights invalidate the greedy argument. The serial number breaks equal-distance ties without comparing vertex labels. Do not mark vertices finished when first discovering them. Citation needed
Practice and recall
-
Why does C’s estimate change from 4 to 3 in the trace?
Work it out before opening the solution. Citation needed
Show the reasoning
- A first offers the direct route to C with cost 4.
- B is processed at distance 1 and offers its edge to C with weight 2.
- The candidate 1 + 2 = 3 improves C before C is finalized.
Citation needed
- What edge-weight assumption makes Dijkstra’s greedy step safe?
- All edge weights are non-negative. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.