Dijkstra's Shortest-Path Algorithm

Dijkstra's algorithm computes shortest-path distances from a single source to all other vertices in a weighted graph with nonnegative edge weights. It repeatedly extracts the unsettled vertex with the smallest tentative distance from a min-heap priority queue, then relaxes its outgoing edges. With predecessor pointers, it also reconstructs the actual shortest path.

Step 1 of 157%

Tutorial

The Algorithm

Dijkstra's shortest-path algorithm computes the shortest distance from a source vertex ss to every other vertex in a weighted graph with nonnegative edge weights.

The algorithm maintains a tentative distance d[v]d[v] for every vertex and a set of settled vertices whose distances are finalized.

Algorithm:

  1. Initialize d[s]=0d[s] = 0 and d[v]=d[v] = \infty for all vsv \neq s.
  2. While an unsettled vertex remains:
    • Extract the unsettled vertex uu with the smallest d[u]d[u] and mark it settled.
    • For each edge (u,v)(u, v) of weight ww, relax: if d[u]+w<d[v]d[u] + w < d[v], set d[v]d[u]+wd[v] \leftarrow d[u] + w.

The extract-min step is implemented with a min-heap keyed on d[v]d[v], giving O(logn)O(\log n) per extraction.

Tiny trace. Consider three vertices with edges AB:4A\text{--}B: 4, AC:2A\text{--}C: 2, BC:1B\text{--}C: 1, starting from AA:

Settle A (d=0):d[B]4, d[C]2.Settle C (d=2):d[B]=min(4,2+1)=3.Settle B (d=3).\begin{align*} \text{Settle } A\ (d=0): &\quad d[B] \leftarrow 4,\ d[C] \leftarrow 2. \\ \text{Settle } C\ (d=2): &\quad d[B] = \min(4,\,2+1) = 3. \\ \text{Settle } B\ (d=3). & \end{align*}

Final distances from AA: d[A]=0, d[B]=3, d[C]=2d[A]=0,\ d[B]=3,\ d[C]=2.

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