Dijkstra's & Bellman-Ford
Watch the shortest-path cloud expand from source A
Use arrow keys or buttons to navigate
Given a weighted graph, find the path with the minimum total weight.
Your GPS finds the route with the least total travel time, not fewest turns. Each road segment has a "weight" (time).
Click any two nodes to see all paths and the shortest one highlighted.
From one source to all other vertices.
Between every pair of vertices.
This deck covers single-source algorithms: Dijkstra's and Bellman-Ford — the most common shortest-path scenario.
Invented by Edsger Dijkstra in 1956. The core idea is a greedy strategy:
A "cloud" of certainty expands from the source. The closest unvisited vertex joins the cloud. Once inside, its shortest distance is guaranteed correct.
dist[] — best-known distance | parent[] — predecessor | PQ — min-priority queue
The fundamental operation in shortest-path algorithms
Relaxing edge (u, v) means checking:
If yes: shorter path found via u → update!
If no: current path to v is already better.
Think of dist[v] as an overestimate that we gradually "relax" (tighten) downward until it reaches the true shortest distance.
Vertices are processed in increasing order of their shortest distance from the source.
Dijkstra gives us the distance to every vertex. To find the actual path, trace the parent[] array backwards.
The parent pointers form a tree rooted at the source. Every path in this tree is a shortest path.
Click any destination node to trace the path back to A.
Why the greedy choice is safe
When Dijkstra's extracts vertex u from the PQ, dist[u] equals the true shortest-path distance.
u is the first vertex extracted with wrong distancedist[y] ≤ true dist to ydist[y] ≤ true dist to udist[u] ≤ dist[y]dist[u] ≤ true dist to u → contradiction!This proof requires all edge weights ≥ 0. Negative edges break the "cloud" property.
| Operation | Count | Cost | Total |
|---|---|---|---|
| extractMin | V | O(log V) | O(V log V) |
| insert/decreaseKey | E | O(log V) | O(E log V) |
For connected graphs (E ≥ V), simplifies to O(E log V).
| Operation | Count | Cost | Total |
|---|---|---|---|
| findMin (scan) | V | O(V) | O(V²) |
| update dist | E | O(1) | O(E) |
Simpler but slower. Better only for dense graphs (E ≈ V²).
Once a vertex is finalized, Dijkstra never reconsiders it. A negative edge can create a shorter path after finalization.
Dijkstra finalizes B with dist=1, but the path A→C→B costs -1. Once finalized, B is never reconsidered.
Dijkstra: dist[B]=1, dist[D]=6
Correct: dist[B]=-1, dist[D]=4
Handles negative edge weights!
Like dropping a stone in a pond — each ripple extends correct distances by one hop. After V-1 ripples, every vertex is reached.
Path A→C→B = 3+(-4) = -1. This is the correct answer that Dijkstra missed!
After V-1 iterations, do one more relaxation pass:
A shortest path (without cycles) has at most V-1 edges. Each iteration correctly extends paths by one edge. If distances still decrease after V-1, a negative cycle must exist.
A cycle where the total weight is negative. Each trip around makes the cost lower — approaching -∞.
If you can reach a negative cycle from the source, and your destination is reachable from the cycle:
Currency exchange where USD→EUR→GBP→USD gives you more money. You'd loop forever for infinite profit. That's a negative cycle!
Negative edges are fine (Bellman-Ford handles them). Negative cycles make the problem undefined.
Choosing the right algorithm
Given this graph with source S, predict the order Dijkstra processes vertices.
Edges: S-A:3, S-B:7, S-C:5, A-B:1, A-D:6, C-D:2
Enter the processing order (e.g., S,A,B,C,D):
This Dijkstra implementation has a bug. What happens if we remove the visited check?
For each scenario, pick the best shortest-path algorithm.
Road distances are always positive. Need fastest route.
Exchange rates → negative log weights. Need to find profitable loops.
10 vertices, ~90 edges, need distances between every pair.
Some links give credits (negative cost). No negative cycles guaranteed.
Google Maps, Waze use Dijkstra variants (A*, contraction hierarchies).
OSPF protocol uses Dijkstra to compute shortest paths between routers.
A* (Dijkstra + heuristic) finds cheapest path avoiding walls, preferring grass.
Convert weights to -log(rate). Negative cycle = profit loop!
Bellman-Ford detects: USD→EUR→GBP→USD > 1.0 → arbitrage!
With a binary heap on a sparse connected graph (E ≈ V)?
How many iterations does Bellman-Ford's main loop run?
Which makes shortest path undefined?
Run Bellman-Ford on this graph (source = A).
Edge order: (A,B,6) (A,C,4) (B,C,-3) (B,D,2) (C,D,5)
What does this Java code print?
Enter the final dist[] array (5 values):