Dijkstra’s shortest paths
Find minimum-cost paths when edges have different nonnegative weights.
Track tentative costs
Give the source distance zero and every other vertex an infinite tentative distance. Repeatedly choose the unsettled vertex whose tentative distance is smallest. If no reachable vertex remains, stop.
How it works
Keep one tentative distance per vertex and pick the vertex with the smallest known distance. From there, check whether each outgoing edge offers a shorter route. The priority queue selects which tentative distance to examine next. Nonnegative weights make that selection safe.
Relax each outgoing edge
For an edge with cost w from the chosen vertex u to v, try distance[u] + w as a candidate for v. Keep the cheaper of that candidate and v’s existing distance. Nonnegative edge weights ensure that settling the cheapest vertex cannot hide a cheaper later route to it.
Choose how to find the cheapest vertex
The example scans all vertices for the next unsettled minimum. With adjacency lists this uses O(V² + E) time. A priority queue can improve performance on sparse graphs, and a negative edge calls for an algorithm with different assumptions.
Code example
graph = [[(1, 7), (2, 2)], [], [(1, 1)]]
size = len(graph)
distance = [float("inf")] * size
settled = [False] * size
distance[0] = 0
for _ in range(size):
current = min((i for i in range(size) if not settled[i]), key=distance.__getitem__)
if distance[current] == float("inf"):
break
settled[current] = True
for neighbor, cost in graph[current]:
distance[neighbor] = min(distance[neighbor], distance[current] + cost)
print(distance[1])Check your understanding
Find the cost of the cheapest route from A to B along the listed directed edges.
See the example and explanation
- Example 1
- Given
A→B: 7, A→C: 2, C→B: 1 - Answer
3 - Example 2
- Given
A→B: 2, A→C: 3, C→B: 2 - Answer
2
The first graph offers cost 7 directly or cost 2 + 1 through C, for a minimum of 3. In the second graph the direct cost 2 is cheaper than 3 + 2.