Docsity

Shortest Paths Algorithms: Dijkstra, Bellman-Ford, and A*, Study notes of Algorithms and Programming

Toggle sidebar
bg1
Algorithms Lecture 13: Shortest Paths
Well, ya turn left by the fire station in the village and take the
old post road by the reservoir and. . . no, that won’t do.
Best to continue straight on by the tar road until you reach the
schoolhouse and then turn left on the road to Bennett’s Lake
until. . . no, that won’t work either.
East Millinocket, ya say? Come to think of it, you can’t get there
from here.
— Robert Bryan and Marshall Dodge,
Bert and I and Other Stories from Down East (1961)
Hey farmer! Where does this road go?
Been livin’ here all my life, it ain’t gone nowhere yet.
Hey farmer! How do you get to Little Rock?
Listen stranger, you can’t get there from here.
Hey farmer! You don’t know very much do you?
No, but I ain’t lost.
— Michelle Shocked, “Arkansas Traveler” (1992)
13 Shortest Paths
13.1 Introduction
Given a weighted directed graph G= (V, E , w)with two special vertices, a source sand a target t,
we want to find the shortest directed path from sto t. In other words, we want to find the path p
starting at sand ending at tminimizing the function
w(p) = X
e∈p
w(e).
For example, if I want to answer the question ‘What’s the fastest way to drive from my old apartment
in Champaign, Illinois to my wife’s old apartment in Columbus, Ohio?’, we might use a graph whose
vertices are cities, edges are roads, weights are driving times, sis Champaign, and tis Columbus.1
The graph is directed since the driving times along the same road might be different in different
directions.2
Perhaps counter to intuition, we will allow the weights on the edges to be negative. Negative
edges make our lives complicated, since the presence of a negative cycle might mean that there is
no shortest path. In general, a shortest path from sto texists if and only if there is at least one path
from sto t, but there is no path from sto tthat touches a negative cycle. If there is a negative cycle
between sand t, then se can always find a shorter path by going around the cycle one more time.
s t
5
2 −8
4 1
3
There is no shortest path from sto t.
1West on Church, north on Prospect, east on I-74, south on I-465, east on Airport Expressway, north on I-65, east on
I-70, north on Grandview, east on 5th, north on Olentangy River, east on Dodridge, north on High, west on Kelso, south
on Neil. Depending on traffic. We both live in Urbana now.
2There is a speed trap on I-70 just inside the Ohio border, but only for eastbound traffic.
1
pf3
pf4
pf5

Partial preview of the text

Download Shortest Paths Algorithms: Dijkstra, Bellman-Ford, and A* and more Study notes Algorithms and Programming in PDF only on Docsity!

Well, ya turn left by the fire station in the village and take the old post road by the reservoir and... no, that won’t do. Best to continue straight on by the tar road until you reach the schoolhouse and then turn left on the road to Bennett’s Lake until... no, that won’t work either. East Millinocket, ya say? Come to think of it, you can’t get there from here. — Robert Bryan and Marshall Dodge, Bert and I and Other Stories from Down East (1961) Hey farmer! Where does this road go? Been livin’ here all my life, it ain’t gone nowhere yet. Hey farmer! How do you get to Little Rock? Listen stranger, you can’t get there from here. Hey farmer! You don’t know very much do you? No, but I ain’t lost. — Michelle Shocked, “Arkansas Traveler” (1992)

13 Shortest Paths

13.1 Introduction

Given a weighted directed graph G = (V, E, w) with two special vertices, a source s and a target t, we want to find the shortest directed path from s to t. In other words, we want to find the path p starting at s and ending at t minimizing the function

w(p) =

e∈p

w(e).

For example, if I want to answer the question ‘What’s the fastest way to drive from my old apartment in Champaign, Illinois to my wife’s old apartment in Columbus, Ohio?’, we might use a graph whose vertices are cities, edges are roads, weights are driving times, s is Champaign, and t is Columbus.^1 The graph is directed since the driving times along the same road might be different in different directions.^2 Perhaps counter to intuition, we will allow the weights on the edges to be negative. Negative edges make our lives complicated, since the presence of a negative cycle might mean that there is no shortest path. In general, a shortest path from s to t exists if and only if there is at least one path from s to t, but there is no path from s to t that touches a negative cycle. If there is a negative cycle between s and t, then se can always find a shorter path by going around the cycle one more time.

s 5 t

2 −

4 1

3

There is no shortest path from s to t. (^1) West on Church, north on Prospect, east on I-74, south on I-465, east on Airport Expressway, north on I-65, east on I-70, north on Grandview, east on 5th, north on Olentangy River, east on Dodridge, north on High, west on Kelso, south on Neil. Depending on traffic. We both live in Urbana now. (^2) There is a speed trap on I-70 just inside the Ohio border, but only for eastbound traffic.

Every algorithm known for solving this problem actually solves (large portions of) the following more general single source shortest path or SSSP problem: find the shortest path from the source vertex s to every other vertex in the graph. In fact, the problem is usually solved by finding a shortest path tree rooted at s that contains all the desired shortest paths. It’s not hard to see that if shortest paths are unique, then they form a tree. To prove this, it’s enough to observe that any subpath of a shortest path is also a shortest path. If there are multiple shortest paths to the same vertices, we can always choose one path to each vertex so that the union of the paths is a tree. If there are shortest paths to two vertices u and v that diverge, then meet, then diverge again, we can modify one of the paths so that the two paths only diverge once.

s

u

v

a

b c

d

x y If s → a → b → c → d → v and s → a → x → y → d → u are both shortest paths, then s → a → b → c → d → u is also a shortest path.

Shortest path trees and minimum spanning trees are usually very different. For one thing, there is only one minimum spanning tree, but in general, there is a different shortest path tree for every source vertex. Moreover, in general, all of these shortest path trees are different from the minimum spanning tree.

8 5 10 2 3 18 16 12 14

30

4 26

8 5 10 2 3 18 16 12 14

30

4 26

A minimum spanning tree and a shortest path tree (rooted at the topmost vertex) of the same graph.

All of the algorithms I’m describing in this lecture also work for undirected graphs, with some slight modifications. Most importantly, we must specifically prohibit alternating back and forth across the same undirected negative-weight edge. Our unmodified algorithms would interpret any such edge as a negative cycle of length 2. To emphasize the direction, I will consistently use the nonstandard notation u → v to denote a directed edge from u to v.

13.2 The Only SSSP Algorithm

Just like graph traversal and minimum spanning trees, there are several different SSSP algorithms, but they are all special cases of the a single generic algorithm, first proposed by Ford in 1956, and independently by Dantzig in 1957.^3 Each vertex v in the graph stores two values, which (inductively) describe a tentative shortest path from s to v. (^3) Specifically, Dantzig showed that the shortest path problem can be phrased as a linear programming problem, and then described an interpretation of the simplex method (which Dantzig discovered) in terms of the original graph. His description was equivalent to Ford’s relaxation strategy.

Just as with graph traversal, using different data structures for the ‘bag’ gives us different algo- rithms. There are three obvious choices to try: a stack, a queue, and a heap. Unfortunately, if we use a stack, we have to perform Θ(2V^ ) relaxation steps in the worst case! (Proving this is a good homework problem.) The other two possibilities are much more efficient.

13.3 Dijkstra’s Algorithm

If we implement the bag as a heap, where the key of a vertex v is dist (v), we obtain an algorithm first ‘published’^4 by Leyzorek, Gray, Johnson, Ladew, Meaker, Petry, and Seitz in 1957, and then later independently rediscovered by Edsger Dijkstra in 1959. A very similar algorithm was also described by Dantzig in 1958. Dijkstra’s algorithm, as it is universally known^5 , is particularly well-behaved if the graph has no negative-weight edges. In this case, it’s not hard to show (by induction, of course) that the vertices are scanned in increasing order of their shortest-path distance from s. It follows that each vertex is scanned at most once, and thus that each edge is relaxed at most once. Since the key of each vertex in the heap is its tentative distance from s, the algorithm performs a DECREASEKEY operation every time an edge is relaxed. Thus, the algorithm performs at most E DECREASEKEYs. Similarly, there are at most V INSERT and EXTRACTMIN operations. Thus, if we store the vertices in a Fibonacci heap, the total running time of Dijkstra’s algorithm is O(E + V log V ).

1

3 2

0 5 10 12 8 4 6 3

7

s

∞

∞

∞

∞

4

3

1

3 2

0 5 10 12 8 4 6 3

7

s

0

∞

∞

∞

∞

∞

∞

1

3 2

0 5 10 12 8 4 6 3

7

s

∞

∞

∞

4

3

12

1

3 2

0 5 10 12 8 4 6 3

7

s

∞

∞

4

3

(^149)

3 2

0 5 10 12 8 4 6 3

7

s

4

3

4 9

7

14

0 0

0 0

Four phases of Dijkstra’s algorithm run on a graph with no negative edges. At each phase, the shaded vertices are in the heap, and the bold vertex has just been scanned. The bold edges describe the evolving shortest path tree. (^4) in the first annual report on a research project performed for the Combat Development Department of the Army Electronic Proving Ground (^5) I will follow this common convention, despite the historical inaccuracy, because I don’t think anybody wants to read about the ”Leyzorek-Gray-Johnson-Ladew-Meaker-Petry-Seitz algorithm”.

This analysis assumes that no edge has negative weight. Dijkstra’s algorithm (in the form I’m presenting here) is still correct if there are negative edges^6 , but the worst-case running time could be exponential. (Proving this unfortunate fact is a good homework problem.)

13.4 The A∗^ Heuristic

A slight generalization of Dijkstra’s algorithm, commonly known as the A∗^ algorithm, is frequently used to find a shortest path from a single source node s to a single target node t. A∗^ uses a black- box function GUESSDISTANCE(v, t) that returns an estimate of the distance from v to t. The only difference between Dijkstra and A∗^ is that the key of a vertex v is dist (v) + GUESSDISTANCE(v, t). The function GUESSDISTANCE is called admissible if GUESSDISTANCE(v, t) never overestimates the actual shortest path distance from v to t. If GUESSDISTANCE is admissible and the actual edge weights are all non-negative, the A∗^ algorithm computes the actual shortest path from s to t at least as quickly as Dijkstra’s algorithm. The closer GUESSDISTANCE(v, t) is to the real distance from v to t, the faster the algorithm. However, in the worst case, the running time is still O(E + V log V ). The heuristic is especially useful in situations where the actual graph is not known. For example, A∗^ can be used to solve puzzles (15-puzzle, Freecell, Shanghai, Sokoban, Atomix, Rush Hour, Rubik’s Cube,... ) and other path planning problems where the starting and goal configurations are given, but the graph of all possible configurations and their connections is not given explicitly.

13.5 Shimbel’s Algorithm (‘Bellman-Ford’)

If we replace the heap in Dijkstra’s algorithm with a queue, we get an algorithm that was first published by Shimbel in 1955, then independently rediscovered by Moore in 1957, by Woodbury and Dantzig in 1957, and by Bellman in 1958. Since Bellman (the Last Discoverer) used the idea of relaxing edges, which was first proposed by Ford in 1956, this is usually called the ‘Bellman-Ford’ algorithm. Shimbel’s algorithm is efficient even if there are negative edges, and it can be used to quickly detect the presence of negative cycles. If there are no negative edges, however, Dijkstra’s algorithm is faster. (In fact, in practice, Dijkstra’s algorithm is often faster even for graphs with negative edges.) The easiest way to analyze the algorithm is to break the execution into phases , by introducing an imaginary token. Before we even begin, we insert the token into the queue. The current phase ends when we take the token out of the queue; we begin the next phase by reinserting the token into the queue. The 0 th phase consists entirely of scanning the source vertex s. The algorithm ends when the queue contains only the token. A simple inductive argument (hint, hint) implies the following invariant:

At the end of the ith phase, for every vertex v, dist (v) is less than or equal to the length of the shortest path s ; v consisting of i or fewer edges.

Since a shortest path can only pass through each vertex once, either the algorithm halts before the V th phase, or the graph contains a negative cycle. In each phase, we scan each vertex at most once, so we relax each edge at most once, so the running time of a single phase is O(E). Thus, the

overall running time of Shimbel’s algorithm is O(V E).

(^6) Some textbooks (like CLRS) present a version of Dijkstra’s algorithm that gives incorrect results for graphs with negative edges.

13.6 Greedy Relaxation?

Here’s another algorithm that fits our generic framework, but which I’ve never seen analyzed.

Repeatedly relax the tensest edge.

Specifically, let’s define the ‘tension’ of an edge u → v as follows:

tension (u → v) = max { 0 , dist (v) − dist (u) − w(u → v)}

(This is defined even when dist (v) = ∞ or dist (u) = ∞, as long as we treat ∞ just like some indescribably large but finite number.) If an edge has zero tension, it’s not tense. If we relax an edge u → v, then dist (v) decreases tension (u → v) and tension (u → v) becomes zero. Intuitively, we can keep the edges of the graph in some sort of heap, where the key of each edge is its tension. Then we repeatedly pull out the tensest edge u → v and relax it. Then we need to recompute the tension of other edges adjacent to v. Edges leaving v possibly become more tense, and edges coming into v possibly become less tense. So we need a heap that efficiently supports the operations INSERT, EXTRACTMAX, INCREASEKEY, and DECREASEKEY. If there are no negative cycles, this algorithm eventually halts with a shortest path tree, but how quickly? Can the same edge be relaxed more than once, and if so, how many times? Is it faster if all the edge weights are positive? Hmm.... This sounds like a good extra credit problem!^8

(^8) I first proposed this bizarre algorithm in 1998, the very first time I taught an algorithms class. As far as I know, nobody has even seriously attempted an analysis. Or maybe it has been analyzed, but it requires an exponential (or even unbounded) number of relaxation steps in the worst case, so nobody’s ever bothered to publish it.