13.8 Shortest-paths problems

If you have an unweighted graph, the shortest path between two vertices is the smallest number of edges you have to pass to get from one of the vertices to the other.

If you agument the breadth-first search algorithm from Section 13.4.2 to remember which vertex a visited vertex came from, if will give you the shortest path between the start vertex and any other vertex. However, things become sligthly more complicated if the graph is weighted.

Shortest-paths on weighted graphs

On a road map, a road connecting two towns is typically labeled with its distance. We can model a road network as a directed graph whose edges are labeled with real numbers. These numbers represent the distance (or other cost metric, such as travel time) between two vertices. These labels may be called weights, costs, or distances, depending on the application. Given such a graph, a typical problem is to find the total length of the shortest path between two specified vertices. This is not a trivial problem, because the shortest path may not be along the edge (if any) connecting two vertices, but rather may be along a path involving one or more intermediate vertices.

For example, in Figure 13.12, the cost of the path from AA to BB to DD is 15. The cost of the edge directly from AA to DD is 20. The cost of the path from AA to CC to BB to DD is 10. Thus, the shortest path from AA to DD is 10 (rather than along the edge connecting AA to DD). We use the notation 𝐝(A,D)=10\mathbf{d}(A, D) = 10 to indicate that the shortest distance from AA to DD is 10. In the figure, there is no path from EE to BB, so we set 𝐝(E,B)=\mathbf{d}(E, B) = \infty. We define 𝐰(A,D)=20\mathbf{w}(A, D) = 20 to be the weight of edge (A,D)(A, D), that is, the weight of the direct connection from AA to DD. Because there is no edge from EE to BB, 𝐰(E,B)=\mathbf{w}(E, B) = \infty. Note that 𝐰(D,A)=\mathbf{w}(D, A) = \infty because the graph is directed. We assume that all weights are positive.

Figure 13.12: Example graph for shortest-path definitions