Skip to content
StackDecode
GraphsAnimated

Dijkstra's Algorithm

Always settle the closest unsettled node.

Time

O((V + E) log V)

Extra space

O(V)

Use it for

Shortest paths with non-negative weights.

How it works

  1. Give every node a tentative distance: 0 for the start, ∞ for the rest.
  2. Repeatedly settle the unsettled node with the smallest distance: it can no longer be improved (all weights are non-negative).
  3. Relax each of its edges: if going through this node is shorter, update the neighbour’s distance.
  4. When every reachable node is settled, the distances are final.

Watch it run

Loading animation…