Shortest Paths
Dijkstra, Bellman-Ford, Floyd-Warshall and A* — which to use for which graph, and how each works.
All shortest-path algorithms share one primitive, relaxation: if going through u gives a shorter route to v, update it.
They differ in which edges they relax, and in what order.
| Algorithm | Graph | Time | Notes |
|---|---|---|---|
| BFS | Unweighted | O(V + E) | Graph traversal |
| Dijkstra | Non-negative weights | O((V + E) log V) | The workhorse |
| Bellman-Ford | Negative weights allowed | O(V · E) | Detects negative cycles |
| Floyd-Warshall | All pairs | O(V³) | Simple triple loop; small V |
| A* | Non-negative + heuristic | ≤ Dijkstra | Maps, games, routing |
| DAG relaxation | Directed acyclic | O(V + E) | Relax in topological order |
Dijkstra's algorithm
Greedy: repeatedly take the unvisited vertex with the smallest known distance (a min-heap), finalise it, and relax its edges. Correct because, with non-negative weights, nothing discovered later can produce a shorter path to an already-finalised vertex.
int[] dijkstra(List<List<int[]>> adj, int src) { // adj[u] = list of {v, w}
int[] dist = new int[adj.size()];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
pq.offer(new int[]{src, 0});
while (!pq.isEmpty()) {
int[] top = pq.poll();
int u = top[0], d = top[1];
if (d > dist[u]) continue; // stale entry (lazy deletion)
for (int[] e : adj.get(u)) {
int v = e[0], nd = d + e[1];
if (nd < dist[v]) { // relax
dist[v] = nd;
pq.offer(new int[]{v, nd});
}
}
}
return dist;
}import heapq
def dijkstra(adj, src): # adj[u] = [(v, w), ...]
dist = {src: 0}
pq = [(0, src)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float("inf")):
continue # stale entry
for v, w in adj[u]:
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(pq, (nd, v))
return distfunction dijkstra(adj: [number, number][][], src: number): number[] {
const dist = new Array(adj.length).fill(Infinity);
dist[src] = 0;
const pq = new MinHeap<[number, number]>((a, b) => a[1] - b[1]); // see the Heaps lesson
pq.push([src, 0]);
while (pq.size) {
const [u, d] = pq.pop()!;
if (d > dist[u]) continue; // stale entry
for (const [v, w] of adj[u]) {
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push([v, dist[v]]);
}
}
}
return dist;
}To recover the path itself, record prev[v] = u on every successful relaxation and walk back from the target.
Bellman-Ford
Relax every edge, V − 1 times. Any shortest path has at most V − 1 edges, so after V − 1 rounds all distances are final. If a V-th round still improves something, a negative cycle is reachable (no shortest path exists).
int[] bellmanFord(int n, int[][] edges, int src) { // edges: {u, v, w}
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int i = 0; i < n - 1; i++)
for (int[] e : edges)
if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]])
dist[e[1]] = dist[e[0]] + e[2];
for (int[] e : edges) // one more round
if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]])
throw new IllegalStateException("negative cycle");
return dist;
}def bellman_ford(n, edges, src):
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError("negative cycle")
return distfunction bellmanFord(n: number, edges: [number, number, number][], src: number): number[] {
const dist = new Array(n).fill(Infinity);
dist[src] = 0;
for (let i = 0; i < n - 1; i++)
for (const [u, v, w] of edges) if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
for (const [u, v, w] of edges) if (dist[u] + w < dist[v]) throw new Error("negative cycle");
return dist;
}Interview twist — "cheapest flights within K stops": run Bellman-Ford for exactly K + 1 rounds, relaxing from a copy of the previous round's distances so each round adds at most one edge.
Bellman-Ford's idea is used in the distance-vector routing protocol RIP (Routing); Dijkstra is used by link-state protocols like OSPF.
Floyd-Warshall (all pairs)
dist[i][j] via intermediate vertices 0..k: allow vertex k as a stepping stone, for each k in turn.
void floydWarshall(long[][] d) { // d[i][j] = weight or INF, d[i][i] = 0
int n = d.length;
for (int k = 0; k < n; k++) // k MUST be the outer loop
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
}def floyd_warshall(d):
n = len(d)
for k in range(n): # k must be the outer loop
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]function floydWarshall(d: number[][]) {
const n = d.length;
for (let k = 0; k < n; k++)
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++)
if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
}A negative value on the diagonal afterwards means a negative cycle.
A* search
Dijkstra explores in all directions. A* orders the priority queue by g(n) + h(n): the known cost so far plus a heuristic estimate of the remaining cost (e.g. straight-line distance on a map). If h never overestimates (admissible), A* still finds the optimal path while exploring far fewer nodes. With h = 0 it is exactly Dijkstra.
- Everything is relaxation; algorithms differ in order.
- Unweighted → BFS. Non-negative → Dijkstra with a heap. Negative edges → Bellman-Ford. All pairs, small V → Floyd-Warshall. Good heuristic → A*.
- Use lazy deletion in Dijkstra: skip popped entries whose distance is stale.
- Store
prev[]to reconstruct paths.
QNetwork delay time: how long until all nodes receive a signal from k?medium
Dijkstra from k; the answer is the maximum finite distance, or −1 if any node is unreachable.
QPath with minimum effort (minimise the maximum height difference along a grid path).medium
Dijkstra where a path's cost is the max edge weight on it instead of the sum: relax with max(dist[u], |h[u] − h[v]|). Alternatively binary search the answer + BFS, or Union-Find over sorted edges.
QWhy is Dijkstra O((V + E) log V)?medium
Each vertex is extracted from the heap once and each edge can push at most one entry, so there are O(V + E) heap operations at O(log V) each (log E = O(log V) because E ≤ V²). With a Fibonacci heap it's O(E + V log V).