Shortest Paths

Dijkstra, Bellman-Ford, Floyd-Warshall and A* — which to use for which graph, and how each works.

Advanced 3 min readLesson 12 of 18 Interview Q&A

All shortest-path algorithms share one primitive, relaxation: if going through u gives a shorter route to v, update it.

if dist[u]+w(u,v)<dist[v] then dist[v]←dist[u]+w(u,v)\text{if } dist[u] + w(u, v) < dist[v] \text{ then } dist[v] \leftarrow dist[u] + w(u, v)

They differ in which edges they relax, and in what order.

AlgorithmGraphTimeNotes
BFSUnweightedO(V + E)Graph traversal
DijkstraNon-negative weightsO((V + E) log V)The workhorse
Bellman-FordNegative weights allowedO(V · E)Detects negative cycles
Floyd-WarshallAll pairsO(V³)Simple triple loop; small V
A*Non-negative + heuristic≤ DijkstraMaps, games, routing
DAG relaxationDirected acyclicO(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.

InteractiveDijkstra's shortest paths
421583263412A0B∞C∞D∞E∞F∞G∞H∞
priority queue
A
visited order
none
currentin priority queuevisited / final
dist[A] = 0, everything else ∞
1/19
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;
}

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;
}

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];
}

A negative value on the diagonal afterwards means a negative cycle.

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.

Key takeaways
  • 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.
Interview questions
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).