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.
- Just settled
- Settled
- In queue
- Not reached
- Current predecessor edge
- Final shortest path
| From | To | Weight |
|---|---|---|
| A | B | 4 |
| A | C | 2 |
| B | C | 1 |
| B | D | 5 |
| C | D | 8 |
| C | E | 10 |
| D | E | 2 |
| D | F | 6 |
| E | F | 3 |
| Node | Distance | Predecessor | State |
|---|---|---|---|
| A | 0 | — | 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.