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.

Step 1 of 157%

Tutorial

Dijkstra's Algorithm

Dijkstra's algorithm computes the shortest-path distance from a source vertex ss to every other vertex in a graph with non-negative edge weights w(u,v)0w(u,v) \geq 0.

Each vertex vv carries a tentative label d(v)d(v), the length of the shortest path from ss to vv found so far. Vertices are split into visited (label finalized) and unvisited (label may still decrease).

Algorithm:

  1. Initialize d(s)=0d(s) = 0 and d(v)=d(v) = \infty for all vsv \neq s. Mark every vertex unvisited.
  2. While some vertex is unvisited:
    • Let uu be the unvisited vertex with the smallest label d(u)d(u).
    • For each outgoing edge (u,v)(u, v), relax: if d(u)+w(u,v)<d(v)d(u) + w(u,v) < d(v), update
d(v)d(u)+w(u,v).d(v) \leftarrow d(u) + w(u,v).
  • Mark uu as visited.

When all vertices are visited, d(v)d(v) equals the true shortest-path distance from ss to vv.

Why non-negative weights? When uu is selected with the smallest unvisited label, no path through other unvisited vertices can reach uu more cheaply: any such alternative crosses an unvisited vertex with label d(u)\geq d(u), and the remaining edges contribute non-negative weight. Negative edges would invalidate this guarantee.

navigate · Enter open · Esc close · ⌘K/Ctrl K toggle