Learn / Graphs

Shortest paths

With equal edge weights use BFS. With non-negative weights use Dijkstra: always settle the closest unsettled vertex, using a min-heap. With negative weights use Bellman-Ford, n - 1 rounds of relaxing every edge, which also detects negative cycles. For all pairs on small graphs, Floyd-Warshall tries every vertex as a stop. Many puzzles are shortest paths on a graph of states.

How to recognise it

  • The fewest steps, the cheapest cost or the smallest effort.
  • Weights that are all 1, all non-negative, or sometimes negative.
  • States like jug contents, words or board squares, joined by moves.

Choosing the algorithm

412150123
From 0: the shortest distances are 0 → 0, 2 → 1, 1 → 3 (through 2), 3 → 4 (through 2 and 1). The direct edge 0-1 (weight 4) is not on any shortest path.
WeightsAlgorithmTime
all equalBFSO(V + E)
0 or 10-1 BFS (deque)O(V + E)
non-negativeDijkstra (min-heap)O(E log V)
any, single sourceBellman-FordO(V E)
DAGrelax in topological orderO(V + E)
all pairs, small VFloyd-WarshallO(V³)
dijkstra(s): dist[s] = 0; heap = [(0, s)]
    while heap: (d, u) = pop; if d > dist[u]: skip
        for (v, w): if d + w < dist[v]: dist[v] = d + w; push (dist[v], v)

Vertices, edges, adjacency lists and the other words used here are on the Structures page.

Variations

  • Count shortest paths: add counts on equal distances, reset on strictly shorter ones.
  • Limited stops: Bellman-Ford rounds, or BFS by number of edges.
  • Minimum effort: Dijkstra where a path costs its largest step, not its sum.
  • Print the path: remember each vertex's parent and walk back.

Common mistakes

  • Using Dijkstra with negative weights.
  • Not skipping stale heap entries.

Problems

0 of 18 solved

Check yourself

Which algorithm handles negative edge weights?

In the pictured graph, what is the shortest distance from 0 to 1?

When does Bellman-Ford report a negative cycle?

Edges of weight 0 and 1 only: what is faster than Dijkstra?