9.5 Shortest-Paths Problems
9.5.1 Shortest-Paths on Unweighted Graphs
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 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.
9.5.2 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 #DistExamp, the cost of the path from to to is 15. The cost of the edge directly from to is 20. The cost of the path from to to to is 10. Thus, the shortest path from to is 10 (rather than along the edge connecting to ). We use the notation to indicate that the shortest distance from to is 10. In the figure, there is no path from to , so we set . We define to be the weight of edge , that is, the weight of the direct connection from to . Because there is no edge from to , . Note that because the graph is directed. We assume that all weights are positive.
Example graph for shortest-path definitions.
9.5.3 Single-Source Shortest Paths
We will now present an algorithm to solve the single-source shortest paths problem. Given Vertex in Graph , find a shortest path from to every other vertex in . We might want only the shortest path between two vertices, and . However in the worst case, finding the shortest path from to requires us to find the shortest paths from to every other vertex as well. So there is no better algorithm (in the worst case) for finding the shortest path to a single vertex than to find shortest paths to all vertices. The algorithm described here will only compute the distance to every such vertex, rather than recording the actual path. Recording the path requires only simple modifications to the algorithm.
Computer networks provide an application for the single-source shortest-paths problem. The goal is to find the cheapest way for one computer to broadcast a message to all other computers on the network. The network can be modeled by a graph with edge weights indicating time or cost to send a message to a neighboring computer.
For unweighted graphs (or whenever all edges have the same cost), the single-source shortest paths can be found using a simple breadth-first search. When weights are added, BFS will not give the correct answer.
One approach to solving this problem when the edges have differing weights might be to process the vertices in a fixed order. Label the vertices to , with . When processing Vertex , we take the edge connecting and . When processing , we consider the shortest distance from to and compare that to the shortest distance from to to . When processing Vertex , we consider the shortest path for Vertices through that have already been processed. Unfortunately, the true shortest path to might go through Vertex for . Such a path will not be considered by this algorithm. However, the problem would not occur if we process the vertices in order of distance from . Assume that we have processed in order of distance from to the first vertices that are closest to ; call this set of vertices . We are now about to process the th closest vertex; call it .
A shortest path from to must have its next-to-last vertex in . Thus,
In other words, the shortest path from to is the minimum over all paths that go from to , then have an edge from to , where is some vertex in .
This solution is usually referred to as Dijkstraβs algorithm. It
works by maintaining a distance estimate
for all vertices
in
.
The elements of
are initialized to the value
(positive infinity). Vertices are processed in order of distance from
.
Whenever a vertex
is processed,
is updated for every neighbor
of
.
Here is an implementation for Dijkstraβs algorithm. At the end, array
D
will contain the shortest distance values.
// Compute shortest path distances from s
function Dijkstra(G, s):
= new Set()
visited = new Map()
D for each v in G.vertices():
put(v, β) // Initialise distances
D.put(s, 0) // The distance from s to s is 0
D.
repeat G.vertxCount() times: // Process the vertices
= minVertex(G, D, visited) // Find next-closest vertex
v add(v)
visited.if D.get(v) == β:
return D // Vertex v is unreachable
for each e in G.outgoingEdges(v):
= e.end
w = D.get(v) + e.weight
dist if dist < D.get(w): // If the new distance is shorter...
put(w, dist) // ...update w with the new distance
D.return D
There are two reasonable solutions to the key issue of finding the
unvisited vertex with minimum distance value during each pass through
the main for
loop. The first method is simply to scan
through the list of
vertices searching for the minimum value, as follows:
// Find the unvisited vertex with the smalled distance
function minVertex(G, D, visited):
= null
minV for each v in G.vertices():
if v not in visited:
if minV is null or D.get(v) < D.get(minV):
= v
minV return minV
Because this scan is done
times, and because each edge requires a constant-time update to
D
, the total cost for this approach is
, because
is in
.
An alternative approach is to store unprocessed vertices in a
min-heap ordered by their distance from the processed vertices. The
next-closest vertex can be found in the heap in
time. Every time we modify
,
we could reorder
in the heap by deleting and reinserting it. This is an example of a priority
queue with priority update. To implement true priority updating, we
would need to store with each vertex its position within the heap so
that we can remove its old distances whenever it is updated by
processing new edges. A simpler approach is to add the new (always
smaller) distance value for a given vertex as a new record in the heap.
The smallest value for a given vertex currently in the heap will be
found first, and greater distance values found later will be ignored
because the vertex will already be marked as visited.
The only disadvantage to repeatedly inserting distance values in this
way is that it will raise the number of elements in the heap from
to
in the worst case. But in practice this only adds a slight increase to
the depth of the heap. The time complexity is
,
because for each edge that we process we must reorder the heap. We use
the KVPair
class to store key-value pairs in the heap, with
the edge weight as the key and the target vertex as the value. here is
the implementation for Dijkstraβs algorithm using a heap.
// Dijkstra's shortest-paths: priority queue version
function DijkstraPQ(G, s):
= new Set()
visited = new Map()
D for (V v : G.vertices())
put(v, β) // Initialize distance
D.put(s, 0) // The distance from s to s is 0
D.
= new PriorityQueue()
agenda add(new KVPair(0, s)) // Initial vertex
agenda.
while not agenda.isEmpty():
= agenda.removeMin().value
v if v not in visited:
add(v)
visited.if D.get(v) == β:
return D // Vertex v is unreachable
for each e in G.outgoingEdges():
= e.end
w = D.get(v) + e.weight
dist if dist < D.get(w): // If the new distance is shorter...
put(w, dist) // ...update w with the new distance...
D.add(new KVPair(dist, w)) // ...and add it to the agenda agenda.
Using minVertex
to scan the vertex list for the minimum
value is more efficient when the graph is dense, that is, when
approaches
.
Using a heap is more efficient when the graph is sparse because its cost
is
.
However, when the graph is dense, this cost can become as great as
.
Now you can practice using Dijkstraβs algorithm.