Lab / graphs

Dijkstra's shortest paths

Always expand the closest unsettled node. With non-negative weights, that one simple rule finds every shortest path from the source.

Edit edge weights

Ready. A starts at distance 0; every other node starts at ∞. The priority queue holds only A.

4215810263Ad=0Bd=∞Cd=∞Dd=∞Ed=∞Fd=∞Gd=∞
  • Just settled
  • Settled
  • In queue
  • Not reached
  • Current predecessor edge
  • Final shortest path
Edges (undirected) with their current weights
FromToWeight
AB4
AC2
BC1
BD5
CD8
CE10
DE2
DF6
EF3
Distances and predecessors after step 0
NodeDistancePredecessorState
A0—in queue
B∞—not reached
C∞—not reached
D∞—not reached
E∞—not reached
F∞—not reached
G∞—not reached

Why it works. With non-negative weights, the node the priority queue returns next can never be reached more cheaply later, so it is settled for good. A negative edge breaks that guarantee, which is why the explorer rejects one instead of showing a wrong answer. With a binary heap the run takes O((V + E) log V) time.

What to look for

  • B is first reached at distance 4 directly from A, then improved to 3 through C. That is a relaxation that changes the predecessor.
  • Node G has no edges, so it stays at ∞. Choose it as the target to see an unreachable result.
  • Type a negative weight to see the input rejected: Dijkstra's algorithm is not correct with negative edges, so the explorer refuses rather than guessing.

Determinism

When two nodes in the queue have the same distance, the one with the smaller id is settled first. Distances only change on a strictly shorter path, so among equally short paths the first one found is kept. Run it twice and you get the same trace.