TL;DR
The shortest-path distance between two vertices of a Graph is the smallest number of edges on any route from one to the other. If the edges carry weights, such as travel times, it is the smallest total weight instead. If no route joins the two vertices, the distance is infinity. It answers questions such as "how many introductions connect these two people?" and "what is the quickest way to get there?"
Builds on: Graph, Breadth-First Search · Leads to: Dijkstra's Algorithm (the weighted case), Average Path Length (the typical distance over all pairs)
Where it's used
Social networks. "Degrees of separation" is a shortest-path distance. Two people are separated by the fewest links in a chain of acquaintances that joins them. Stanley Milgram's letter experiments in the United States in 1967 found completed chains that needed about five or six intermediaries, which gave rise to the phrase "six degrees of separation". Each chain is a route in the acquaintance graph, and the shortest one is a shortest-path distance.
Navigation. A route planner stores roads as a graph whose edges carry travel times. The shortest-path distance from where you are to your destination is the least total time over all routes. Because the edges carry weights, the planner needs a weighted method such as Dijkstra's Algorithm, not a plain edge count.
Deep learning on graphs. The Graphormer model (2021) feeds the shortest-path distance between every pair of nodes into its attention scores as a learned bias. The network therefore knows how far apart two nodes are in the graph, not only what their features are, and this helps it on molecular and other graph datasets.
How it works
Take six vertices, P, Q, R, S, T and U, with five edges: P–Q, Q–R, P–S, S–T and T–R. Vertex U has no edges. The question is: what is the shortest-path distance from P to R?
flowchart LR P --- Q Q --- R P --- S S --- T T --- R U
- Name the question. We want the fewest edges on a route from P to R. A route is a list of vertices in which each neighbouring pair in the list is joined by an edge, and its length is the number of edges in it. Check: a route from P to R with no edges would need P and R to be the same vertex, and they are not.
- List the routes. From P you can go to Q or to S. From Q you can reach R directly, so one route is P, Q, R. From S you go to T, and T joins R, so another route is P, S, T, R. Check: every step in each list follows an edge in the diagram.
- Count the edges. The route P, Q, R has 2 edges. The route P, S, T, R has 3 edges. Check: count the links between neighbours, not the vertices. A list of three vertices has two links.
- Take the smallest. The shortest-path distance from P to R is 2. Check: no route of length 1 exists, because P and R are not joined directly, so 2 is the least possible.
- Do the same from P to every vertex. Q and S are one edge from P, so they are at distance 1. T and R are at distance 2, through S and Q respectively. U has no route from P at all, so its distance is infinity. Check: the distances from P are 0 (P itself), 1, 1, 2, 2 and infinity.
- Run it the other way. From R to P the same two routes appear reversed, with the same lengths, so the distance is still 2. Check: for an undirected graph, the distance from one vertex to another is the same in both directions.
The drawing does not matter. Only the links decide the distance, so the same graph can be drawn in any layout and give the same numbers.
The math
Let be a graph. A walk from a vertex to a vertex is a sequence of vertices in which each consecutive pair is an edge. Its length is , the number of edges it uses. A path is a walk that visits no vertex twice.
For vertices and of a graph, is the minimum length of a walk from to . If no walk exists, .
Step 2 in symbols: the candidate routes
Lengths are whole numbers that cannot be negative, so when a walk exists the smallest length always exists:
Here stands for one walk, and the set in braces lists the lengths of all of them. For the example, the path has length 2 and has length 3, so .
Step 3 in symbols: the minimum is a path with no repeats
Let a walk from to be a sequence of edges that may revisit vertices. If a walk visits some vertex twice, cut out the part between the two visits. What remains is still a walk from to , and it is shorter. So the minimum is always reached by a path that repeats no vertex, and the definition may use paths alone.
Step 4 in symbols: the whole row of distances
Fix one vertex and compute for every . This list is the row of distances from . For an unweighted graph, Breadth-First Search from produces the whole row in time, using Big-O Notation. Each vertex's distance is the layer at which BFS first reaches it.
The same numbers appear in the Adjacency Matrix . The entry counts walks of length from to (see Matrix Multiplication), so for , is the smallest for which that entry is positive.
Three properties
For any vertices , , of an undirected graph:
The first holds because the path with no edges has length 0. The second holds because reversing a path gives a path of the same length. The third is the triangle inequality: join a shortest path from to to a shortest path from to . The result is a walk from to of length , and the shortest path from to is at most that long. Positivity also holds: whenever , because a route between two different vertices has at least one edge. Together with the three properties above, these make a metric.
Weights
If each edge has a weight , define the length of a path as the sum of its edge weights, and let be the minimum of these sums. The definition is unchanged except that "number of edges" becomes "total weight". Counting edges is the special case where every weight is 1.
Worked examples
Vertices X and Y are joined by one edge. Find .
- The route X, Y uses one edge, so its length is 1.
- No route has length 0, because that would need X and Y to be the same vertex.
- So . By symmetry , and .
Interpretation: a single edge is the shortest possible distance between two different vertices.
Vertices 1, 2, 3 and 4 form a square with edges 1–2, 2–3, 3–4 and 4–1. Find first by counting edges, then with weights.
- Counting edges: the route 1, 2, 3 has 2 edges, and the route 1, 4, 3 has 2 edges. Neither is shorter, so .
- Add weights: , , and .
- The route through 2 costs . The route through 4 costs .
- So the weighted distance is , and the cheapest route goes through 4.
Interpretation: the two routes tie when edges are counted, so the count cannot tell them apart. Weights break the tie, and they give a different route to the same number.
Ana knows Ben, and Ben knows Cara, and Cara knows Dev, and Dev knows Eli. Separately, Ana knows Fay, Fay knows Gus, and Gus knows Eli. Find how many introductions connect Ana to Eli.
- The chain Ana, Ben, Cara, Dev, Eli has 4 links.
- The chain Ana, Fay, Gus, Eli has 3 links.
- The shortest-path distance is the smaller of these, .
- So the shortest chain has three links, which means two intermediaries, Fay and Gus.
Try it: Ben and Eli become friends, adding the edge Ben–Eli. What is now?
Answer: 2. The new chain Ana, Ben, Eli has 2 links, and the other chains are still 4 and 3. The minimum is 2, so Ben now introduces Ana to Eli directly.
Common mistakes and tradeoffs
It is tempting to think that the distance is the straight-line distance between two drawn points. In fact the drawing has no meaning. Two vertices drawn next to each other can be far apart in the graph if the only links run round the other side. Distance counts edges or weights, not positions on a page.
It is tempting to think that there is one shortest path. In fact there can be many with the same length, as in Example 2. The distance is unique, but the route is not.
It is tempting to think that vertices with no route between them have distance 0, or can simply be left out. In fact their distance is infinity. Any average or maximum over all pairs must say how it treats these pairs, which matters for Average Path Length.
It is tempting to think that BFS is always enough. In fact BFS counts edges. Once edges carry weights, such as travel times, use Dijkstra's Algorithm. Dijkstra's method also needs non-negative weights; for negative weights, the Bellman–Ford method, which handles them directly, is the usual choice.
When to use it: when you need the fewest steps or the least total cost between two specific vertices. When not to use it: when you need many routes at once, or when you only care whether a route exists at all, which a plain search answers more cheaply. Alternatives: BFS for unweighted graphs, Dijkstra's method for non-negative weights, and the Floyd–Warshall method when the distance between every pair of vertices is wanted at once.
History
People were finding shortest routes through mazes and networks long before the graph language existed. In 1959 Edward Moore described a layer-by-layer search for the shortest path through a maze. In 1961 C. Y. Lee used the same idea to route connections on printed circuit boards. Also in 1959, Edsger Dijkstra published a method for weighted graphs, which is the version that handles weights directly. In 1962 Robert Floyd and Stephen Warshall published separate methods that compute the distance between every pair of vertices.
These methods caught on because the question is simple to state and comes up in so many fields, from transport and telephone networks to the study of social ties.
Recap
- The shortest-path distance between two vertices is the minimum length of a route between them, and it is infinity when no route exists.
- With unweighted edges, length means the number of edges; with weights, it means the total weight.
- The minimum is always reached by a route that repeats no vertex, and the distance is symmetric and obeys the triangle inequality.
- For unweighted graphs, Breadth-First Search gives all distances from one vertex; for non-negative weights, Dijkstra's Algorithm does.
- Read next: Average Path Length, which averages these distances over all pairs, and the Graphormer paper, which uses them inside a neural network.
Check yourself
QuestionRecall: what is the shortest-path distance between two vertices when no path joins them?Show answer
Infinity. There is no route to take the minimum over, so the distance is defined to be infinity, not 0 and not a missing value.
QuestionCompute: a graph has edges A–B, B–C, A–D, D–E and E–C. What is ?Show answer
The route A, B, C has 2 edges. The route A, D, E, C has 3 edges. The minimum is 2, so .
QuestionWhy: why is the shortest route never one that visits the same vertex twice?Show answer
If a route visits a vertex twice, the loop between the two visits can be cut out. The result is still a route from start to end, with fewer edges. So any route with a repeated vertex can be shortened, and the shortest one never has a repeat.
QuestionApplied: a delivery company wants the fewest kilometres from its depot to a customer, on a road network where roads have different lengths. Is counting edges with BFS the right method?Show answer
No. BFS counts road segments, so it finds the route with the fewest segments, which may not be the shortest in kilometres. Each road needs its length as a weight, and a weighted method such as Dijkstra's algorithm then gives the shortest distance in kilometres.
Sources
- Wikipedia, Distance (graph theory)
- Wikipedia, Shortest path problem
- Ying et al., "Do Transformers Really Perform Bad for Graph Representation?" (Graphormer), arXiv:2106.05234