Docsity

Introduction to Algorithms, Lecture Notes - Computer Science - 5, Study notes of Introduction to Computers

Toggle sidebar
bg1
Chapter 4
Paths in graphs
4.1 Distances
Depth-first search readily identifies all the vertices of a graph that can be reached from a
designated starting point. It also finds explicit paths to these vertices, summarized in its
search tree (Figure 4.1). However, these paths might not be the most economical ones possi-
ble. In the figure, vertex Cis reachable from Sby traversing just one edge, while the DFS tree
shows a path of length 3. This chapter is about algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which different vertices of
a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph that has a ball
for each vertex and a piece of string for each edge. If you lift the ball for vertex shigh enough,
the other balls that get pulled up along with it are precisely the vertices reachable from s.
And to find their distances from s, you need only measure how far below sthey hang.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree.
(a)
EA
S
BD C
(b)
S
A
B
D
E
C
115
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download Introduction to Algorithms, Lecture Notes - Computer Science - 5 and more Study notes Introduction to Computers in PDF only on Docsity!

Chapter 4

Paths in graphs

4.1 Distances

Depth-first search readily identifies all the vertices of a graph that can be reached from a designated starting point. It also finds explicit paths to these vertices, summarized in its search tree (Figure 4.1). However, these paths might not be the most economical ones possi- ble. In the figure, vertex C is reachable from S by traversing just one edge, while the DFS tree shows a path of length 3. This chapter is about algorithms for finding shortest paths in graphs.

Path lengths allow us to talk quantitatively about the extent to which different vertices of a graph are separated from each other:

The distance between two nodes is the length of the shortest path between them.

To get a concrete feel for this notion, consider a physical realization of a graph that has a ball for each vertex and a piece of string for each edge. If you lift the ball for vertex s high enough, the other balls that get pulled up along with it are precisely the vertices reachable from s. And to find their distances from s, you need only measure how far below s they hang.

Figure 4.1 (a) A simple graph and (b) its depth-first search tree.

(a)

E S A

D C B

(b) (^) S

A

B

D

E

C

116 Algorithms

Figure 4.2 A physical model of a graph.

B

E S

D C

A

S
C D E
B
A

In Figure 4.2 for example, vertex B is at distance 2 from S, and there are two shortest paths to it. When S is held up, the strings along each of these paths become taut. On the other hand, edge (D, E) plays no role in any shortest path and therefore remains slack.

4.2 Breadth-first search

In Figure 4.2, the lifting of s partitions the graph into layers: s itself, the nodes at distance 1 from it, the nodes at distance 2 from it, and so on. A convenient way to compute distances from s to the other vertices is to proceed layer by layer. Once we have picked out the nodes at distance 0 , 1 , 2 ,... , d, the ones at d + 1 are easily determined: they are precisely the as-yet- unseen nodes that are adjacent to the layer at distance d. This suggests an iterative algorithm in which two layers are active at any given time: some layer d, which has been fully identified, and d + 1, which is being discovered by scanning the neighbors of layer d. Breadth-first search (BFS) directly implements this simple reasoning (Figure 4.3). Ini- tially the queue Q consists only of s, the one node at distance 0. And for each subsequent distance d = 1, 2 , 3 ,.. ., there is a point in time at which Q contains all the nodes at distance d and nothing else. As these nodes are processed (ejected off the front of the queue), their as-yet-unseen neighbors are injected into the end of the queue. Let’s try out this algorithm on our earlier example (Figure 4.1) to confirm that it does the right thing. If S is the starting point and the nodes are ordered alphabetically, they get visited in the sequence shown in Figure 4.4. The breadth-first search tree, on the right, contains the edges through which each node is initially discovered. Unlike the DFS tree we saw earlier, it has the property that all its paths from S are the shortest possible. It is therefore a shortest- path tree.

Correctness and efficiency

We have developed the basic intuition behind breadth-first search. In order to check that the algorithm works correctly, we need to make sure that it faithfully executes this intuition. What we expect, precisely, is that

For each d = 0, 1 , 2 ,.. ., there is a moment at which (1) all nodes at distance ≤ d

118 Algorithms

Figure 4.4 The result of breadth-first search on the graph of Figure 4.1.

Order Queue contents of visitation after processing node [S] S [A C D E] A [C D E B] C [D E B] D [E B] E [B] B [ ]

A D
B
C E
S

Figure 4.5 Edge lengths often matter.

Francisco

San

Los Angeles

Bakersfield

Sacramento

Reno

Las Vegas

409

290

95

271

133

445

291 112

275

4.3 Lengths on edges

Breadth-first search treats all edges as having the same length. This is rarely true in ap- plications where shortest paths are to be found. For instance, suppose you are driving from San Francisco to Las Vegas, and want to find the quickest route. Figure 4.5 shows the major highways you might conceivably use. Picking the right combination of them is a shortest-path problem in which the length of each edge (each stretch of highway) is important. For the re- mainder of this chapter, we will deal with this more general scenario, annotating every edge e ∈ E with a length le. If e = (u, v), we will sometimes also write l(u, v) or luv. These le’s do not have to correspond to physical lengths. They could denote time (driving time between cities) or money (cost of taking a bus), or any other quantity that we would like to conserve. In fact, there are cases in which we need to use negative lengths, but we will briefly overlook this particular complication.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 119

Figure 4.6 Breaking edges into unit-length pieces.

C

A

B

E

D

C E

B D

1 A

2

2

4

(^32) 1

4.4 Dijkstra’s algorithm

4.4.1 An adaptation of breadth-first search

Breadth-first search finds shortest paths in any graph whose edges have unit length. Can we adapt it to a more general graph G = (V, E) whose edge lengths le are positive integers?

A more convenient graph

Here is a simple trick for converting G into something BFS can handle: break G’s long edges into unit-length pieces, by introducing “dummy” nodes. Figure 4.6 shows an example of this transformation. To construct the new graph G′,

For any edge e = (u, v) of E, replace it by le edges of length 1 , by adding le − 1 dummy nodes between u and v.

Graph G′^ contains all the vertices V that interest us, and the distances between them are exactly the same as in G. Most importantly, the edges of G′^ all have unit length. Therefore, we can compute distances in G by running BFS on G′.

Alarm clocks

If efficiency were not an issue, we could stop here. But when G has very long edges, the G′ it engenders is thickly populated with dummy nodes, and the BFS spends most of its time diligently computing distances to these nodes that we don’t care about at all. To see this more concretely, consider the graphs G and G′^ of Figure 4.7, and imagine that the BFS, started at node s of G′, advances by one unit of distance per minute. For the first 99 minutes it tediously progresses along S − A and S − B, an endless desert of dummy nodes. Is there some way we can snooze through these boring phases and have an alarm wake us up whenever something interesting is happening—specifically, whenever one of the real nodes (from the original graph G) is reached? We do this by setting two alarms at the outset, one for node A, set to go off at time T = 100, and one for B, at time T = 200. These are estimated times of arrival , based upon the edges currently being traversed. We doze off and awake at T = 100 to find A has been discovered. At

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 121

Delete-min. Return the element with the smallest key, and remove it from the set.

Make-queue. Build a priority queue out of the given elements, with the given key values. (In many implementations, this is significantly faster than inserting the elements one by one.)

The first two let us set alarms, and the third tells us which alarm is next to go off. Putting this all together, we get Dijkstra’s algorithm (Figure 4.8).

In the code, dist(u) refers to the current alarm clock setting for node u. A value of ∞ means the alarm hasn’t so far been set. There is also a special array, prev, that holds one crucial piece of information for each node u: the identity of the node immediately before it on the shortest path from s to u. By following these back-pointers, we can easily reconstruct shortest paths, and so this array is a compact summary of all the paths found. A full example of the algorithm’s operation, along with the final shortest-path tree, is shown in Figure 4.9.

In summary, we can think of Dijkstra’s algorithm as just BFS, except it uses a priority queue instead of a regular queue, so as to prioritize nodes in a way that takes edge lengths into account. This viewpoint gives a concrete appreciation of how and why the algorithm works, but there is a more direct, more abstract derivation that doesn’t depend upon BFS at all. We now start from scratch with this complementary interpretation.

Figure 4.8 Dijkstra’s shortest-path algorithm.

procedure dijkstra(G, l, s) Input: Graph G = (V, E), directed or undirected; positive edge lengths {le : e ∈ E}; vertex s ∈ V Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u.

for all u ∈ V : dist(u) = ∞ prev(u) = nil dist(s) = 0

H = makequeue (V ) (using dist-values as keys) while H is not empty: u = deletemin(H) for all edges (u, v) ∈ E: if dist(v) > dist(u) + l(u, v): dist(v) = dist(u) + l(u, v) prev(v) = u decreasekey(H, v)

122 Algorithms

Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting point. Also shown are the associated dist values and the final shortest-path tree.

B

C

D

E

A

4 1 3

2

4 1 3

5

2

A: 0 D: ∞
B: 4 E: ∞
C: 2

B

C

D

E

A

4

2

4 1 3

5

2

1 3 A:^0 D:^6
B: 3 E: 7
C: 2

B

C

D

E

A

4

1 3

2

4 1 3

5

2

A: 0 D: 5
B: 3 E: 6
C: 2

B

C

D

E

A

4 1 3

2

1

5

2

3

4 A: 0 D: 5
B: 3 E: 6
C: 2
B
C
D
E
A

2

(^1 )

2

124 Algorithms

Initialize dist(s) to 0, other dist(·) values to ∞ R = { } (the ‘‘known region’’) while R 6 = V : Pick the node v 6 ∈ R with smallest dist(·) Add v to R for all edges (v, z) ∈ E: if dist(z) > dist(v) + l(v, z): dist(z) = dist(v) + l(v, z)

Incorporating priority queue operations gives us back Dijkstra’s algorithm (Figure 4.8). To justify this algorithm formally, we would use a proof by induction, as with breadth-first search. Here’s an appropriate inductive hypothesis.

At the end of each iteration of the while loop, the following conditions hold: (1) there is a value d such that all nodes in R are at distance ≤ d from s and all nodes outside R are at distance ≥ d from s, and (2) for every node u, the value dist(u) is the length of the shortest path from s to u whose intermediate nodes are constrained to be in R (if no such path exists, the value is ∞).

The base case is straightforward (with d = 0), and the details of the inductive step can be filled in from the preceding discussion.

4.4.3 Running time

At the level of abstraction of Figure 4.8, Dijkstra’s algorithm is structurally identical to breadth-first search. However, it is slower because the priority queue primitives are com- putationally more demanding than the constant-time eject’s and inject’s of BFS. Since makequeue takes at most as long as |V | insert operations, we get a total of |V | deletemin and |V | + |E| insert/decreasekey operations. The time needed for these varies by imple- mentation; for instance, a binary heap gives an overall running time of O((|V | + |E|) log |V |).

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 125

Which heap is best?

The running time of Dijkstra’s algorithm depends heavily on the priority queue implemen- tation used. Here are the typical choices.

Implementation deletemin insert/ decreasekey

|V | × deletemin + (|V | + |E|) × insert Array O(|V |) O(1) O(|V |^2 ) Binary heap O(log |V |) O(log |V |) O((|V | + |E|) log |V |) d-ary heap O( d^ log log^ |dV |) O( log log^ |V d^ |) O((|V | · d + |E|) log log^ | Vd^ |) Fibonacci heap O(log |V |) O(1) (amortized) O(|V | log |V | + |E|)

So for instance, even a naive array implementation gives a respectable time complexity of O(|V |^2 ), whereas with a binary heap we get O((|V | + |E|) log |V |). Which is preferable? This depends on whether the graph is sparse (has few edges) or dense (has lots of them). For all graphs, |E| is less than |V |^2. If it is Ω(|V |^2 ), then clearly the array implementation is the faster. On the other hand, the binary heap becomes preferable as soon as |E| dips below |V |^2 / log |V |. The d-ary heap is a generalization of the binary heap (which corresponds to d = 2) and leads to a running time that is a function of d. The optimal choice is d ≈ |E|/|V |; in other words, to optimize we must set the degree of the heap to be equal to the average degree of the graph. This works well for both sparse and dense graphs. For very sparse graphs, in which |E| = O(|V |), the running time is O(|V | log |V |), as good as with a binary heap. For dense graphs, |E| = Ω(|V |^2 ) and the running time is O(|V |^2 ), as good as with a linked list. Finally, for graphs with intermediate density |E| = |V |1+δ^ , the running time is O(|E|), linear! The last line in the table gives running times using a sophisticated data structure called a Fibonacci heap. Although its efficiency is impressive, this data structure requires con- siderably more work to implement than the others, and this tends to dampen its appeal in practice. We will say little about it except to mention a curious feature of its time bounds. Its insert operations take varying amounts of time but are guaranteed to average O(1) over the course of the algorithm. In such situations (one of which we shall encounter in Chapter 5) we say that the amortized cost of heap insert’s is O(1).

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 127

Figure 4.11 (a) A binary heap with 10 elements. Only the key values are shown. (b)–(d) The intermediate “bubble-up” steps in inserting an element with key 7. (e)–(g) The “sift-down” steps in a delete-min operation.

(a) 3

10 5

11 12 6 8

15 20 13

(b) 3

10 5

11 12 6 8

15 20 13 7

(c) 3

10 5

11 6 8

15 20 13 12

7

(d) 3

5

11 6 8

15 20 13 12

7

10

(e)

5

11 6 8

15 20 13 12

7

10

(f)

5

11 6 8

15 20 13

7

10

12

(g)

11 8

15 20 13

7

10 6

5

12

(h)

11 8

15 20 13

7

10

5

6

12

128 Algorithms

Figure 4.12 Dijkstra’s algorithm will not work if there are negative edges.

S
A
B

−

3

4

4.6 Shortest paths in the presence of negative edges

4.6.1 Negative edges

Dijkstra’s algorithm works in part because the shortest path from the starting point s to any node v must pass exclusively through nodes that are closer than v. This no longer holds when edge lengths can be negative. In Figure 4.12, the shortest path from S to A passes through B, a node that is further away! What needs to be changed in order to accommodate this new complication? To answer this, let’s take a particular high-level view of Dijkstra’s algorithm. A crucial invariant is that the dist values it maintains are always either overestimates or exactly correct. They start off at ∞, and the only way they ever change is by updating along an edge:

procedure update((u, v) ∈ E) dist(v) = min{dist(v), dist(u) + l(u, v)}

This update operation is simply an expression of the fact that the distance to v cannot possibly be more than the distance to u, plus l(u, v). It has the following properties.

  1. It gives the correct distance to v in the particular case where u is the second-last node in the shortest path to v, and dist(u) is correctly set.
  2. It will never make dist(v) too small, and in this sense it is safe. For instance, a slew of extraneous update’s can’t hurt.

This operation is extremely useful: it is harmless, and if used carefully, will correctly set distances. In fact, Dijkstra’s algorithm can be thought of simply as a sequence of update’s. We know this particular sequence doesn’t work with negative edges, but is there some other sequence that does? To get a sense of the properties this sequence must possess, let’s pick a node t and look at the shortest path to it from s.

s ^  ^ ^ ^  t

u 1 u 2 u 3 uk

This path can have at most |V | − 1 edges (do you see why?). If the sequence of updates per- formed includes (s, u 1 ), (u 1 , u 2 ), (u 2 , u 3 ),... , (uk , t), in that order (though not necessarily con- secutively), then by the first property the distance to t will be correctly computed. It doesn’t

130 Algorithms

Figure 4.14 The Bellman-Ford algorithm illustrated on a sample graph.

E
B
A
G
F
D
S
C

3

1

1

− 2

2

10

− 1

− 1

− 4 1

(^8) Iteration Node 0 1 2 3 4 5 6 7 S 0 0 0 0 0 0 0 0 A ∞ 10 10 5 5 5 5 5 B ∞ ∞ ∞ 10 6 5 5 5 C ∞ ∞ ∞ ∞ 11 7 6 6 D ∞ ∞ ∞ ∞ ∞ 14 10 9 E ∞ ∞ 12 8 7 7 7 7 F ∞ ∞ 9 9 9 9 9 9 G ∞ 8 8 8 8 8 8 8

4.7 Shortest paths in dags

There are two subclasses of graphs that automatically exclude the possibility of negative cy- cles: graphs without negative edges, and graphs without cycles. We already know how to efficiently handle the former. We will now see how the single-source shortest-path problem can be solved in just linear time on directed acyclic graphs. As before, we need to perform a sequence of updates that includes every shortest path as a subsequence. The key source of efficiency is that

In any path of a dag, the vertices appear in increasing linearized order.

Therefore, it is enough to linearize (that is, topologically sort) the dag by depth-first search, and then visit the vertices in sorted order, updating the edges out of each. The algorithm is given in Figure 4.15.

Notice that our scheme doesn’t require edges to be positive. In particular, we can find longest paths in a dag by the same algorithm: just negate all edge lengths.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 131

Figure 4.15 A single-source shortest-path algorithm for directed acyclic graphs.

procedure dag-shortest-paths(G, l, s) Input: Dag G = (V, E); edge lengths {le : e ∈ E}; vertex s ∈ V Output: For all vertices u reachable from s, dist(u) is set to the distance from s to u.

for all u ∈ V : dist(u) = ∞ prev(u) = nil

dist(s) = 0 Linearize G for each u ∈ V , in linearized order: for all edges (u, v) ∈ E: update(u, v)

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 133

4.5. Often there are multiple shortest paths between two nodes of a graph. Give a linear-time algo- rithm for the following task. Input: Undirected graph G = (V, E) with unit edge lengths; nodes u, v ∈ V. Output: The number of distinct shortest paths from u to v. 4.6. Prove that for the array prev computed by Dijkstra’s algorithm, the edges {u, prev[u]} (for all u ∈ V ) form a tree. 4.7. You are given a directed graph G = (V, E) with (possibly negative) weighted edges, along with a specific node s ∈ V and a tree T = (V, E′), E′^ ⊆ E. Give an algorithm that checks whether T is a shortest-path tree for G with starting point s. Your algorithm should run in linear time. 4.8. Professor F. Lake suggests the following algorithm for finding the shortest path from node s to node t in a directed graph with some negative edges: add a large constant to each edge weight so that all the weights become positive, then run Dijkstra’s algorithm starting at node s, and return the shortest path found to node t. Is this a valid method? Either prove that it works correctly, or give a counterexample. 4.9. Consider a directed graph in which the only negative edges are those that leave s; all other edges are positive. Can Dijkstra’s algorithm, started at s, fail on such a graph? Prove your answer.

4.10. You are given a directed graph with (possibly negative) weighted edges, in which the shortest path between any two vertices is guaranteed to have at most k edges. Give an algorithm that finds the shortest path between two vertices u and v in O(k|E|) time.

4.11. Give an algorithm that takes as input a directed graph with positive edge lengths, and returns the length of the shortest cycle in the graph (if the graph is acyclic, it should say so). Your algorithm should take time at most O(|V |^3 ).

4.12. Give an O(|V |^2 ) algorithm for the following task.

Input: An undirected graph G = (V, E); edge lengths le > 0 ; an edge e ∈ E. Output: The length of the shortest cycle containing edge e.

4.13. You are given a set of cities, along with the pattern of highways between them, in the form of an undirected graph G = (V, E). Each stretch of highway e ∈ E connects two of the cities, and you know its length in miles, le. You want to get from city s to city t. There’s one problem: your car can only hold enough gas to cover L miles. There are gas stations in each city, but not between cities. Therefore, you can only take a route if every one of its edges has length le ≤ L. (a) Given the limitation on your car’s fuel tank capacity, show how to determine in linear time whether there is a feasible route from s to t. (b) You are now planning to buy a new car, and you want to know the minimum fuel tank capacity that is needed to travel from s to t. Give an O((|V | + |E|) log |V |) algorithm to determine this.

4.14. You are given a strongly connected directed graph G = (V, E) with positive edge weights along with a particular node v 0 ∈ V. Give an efficient algorithm for finding shortest paths between all pairs of nodes , with the one restriction that these paths must all pass through v 0.

4.15. Shortest paths are not always unique: sometimes there are two or more different paths with the minimum possible length. Show how to solve the following problem in O((|V | + |E|) log |V |) time.

134 Algorithms

Input: An undirected graph G = (V, E); edge lengths le > 0 ; starting vertex s ∈ V. Output: A Boolean array usp[·]: for each node u, the entry usp[u] should be true if and only if there is a unique shortest path from s to u. (Note: usp[s] = true.)