Shortest Path Algorithms

Find the cheapest route through a weighted graph: BFS for equal weights, Dijkstra for non-negative weights, Bellman-Ford when edges can be negative or the number of hops is limited.

Overview

What a shortest path is

A weighted graph gives every edge a number, its weight. A path's weight is the sum of the weights of its edges. The shortest path between two nodes is the path with the smallest total weight, not the one with the fewest edges. Edsger Dijkstra published the best-known algorithm for it in 1959, and Richard Bellman published the one that also handles negative weights in 1958.

Here is the graph that the rest of this topic traces. Every edge points one way.

Add up each route from S to T. S, A, C, T costs 2 + 3 + 2 = 7. S, B, C, T costs 6 + 1 + 2 = 9, and S, A, B, C, T costs 2 + 4 + 1 + 2 = 9. So the shortest path is S, A, C, T at 7. Counting edges would not have found it: S, B, C, T has just as few edges and costs 9.

Problems rarely say the word graph. The problem arrives as flight prices, network delays, a hiking grid with effort scores, or water rising over a map. The first skill is to see the graph. The second is to read the edge weights and pick the algorithm they allow.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio