Dijkstra's Algorithm for Non-Negative Weights
Compute shortest-path distances and reconstruct shortest paths from a source vertex in a directed graph with non-negative edge weights by running Dijkstra's label-setting algorithm.
Tutorial
Dijkstra's Algorithm
Dijkstra's algorithm computes the shortest-path distance from a source vertex to every other vertex in a graph with non-negative edge weights .
Each vertex carries a tentative label , the length of the shortest path from to found so far. Vertices are split into visited (label finalized) and unvisited (label may still decrease).
Algorithm:
- Initialize and for all . Mark every vertex unvisited.
- While some vertex is unvisited:
- Let be the unvisited vertex with the smallest label .
- For each outgoing edge , relax: if , update
- Mark as visited.
When all vertices are visited, equals the true shortest-path distance from to .
Why non-negative weights? When is selected with the smallest unvisited label, no path through other unvisited vertices can reach more cheaply: any such alternative crosses an unvisited vertex with label , and the remaining edges contribute non-negative weight. Negative edges would invalidate this guarantee.