Dijkstra's Shortest Path visualization

Greedily settle the closest unsettled vertex using a priority queue.

Keep a tentative distance for every vertex. Repeatedly pop the vertex with the smallest distance — that distance is now final — and relax its outgoing edges.

Edge case: it requires non-negative weights. With a negative edge, a "settled" vertex can later get a shorter path, and Dijkstra will report a wrong answer. Use Bellman–Ford instead.

Complexity

Time: best O((V+E) log V), average O((V+E) log V), worst O((V+E) log V). Space: O(V). Difficulty: Intermediate.

Pseudocode

procedure dijkstra(G, s):
  dist[*] ← ∞; dist[s] ← 0; pq ← {(0, s)}
  while pq not empty:
    (d, u) ← pq.popMin()
    if d > dist[u]: continue         // stale entry
    for each (v, w) in G[u]:
      if dist[u] + w < dist[v]:
        dist[v] ← dist[u] + w; prev[v] ← u
        pq.push((dist[v], v))
  return dist, prev

More graphs algorithms