Shortest Path,

Ace your homework & exams now with Quizwiz!

Programming Dijkstra's Algorithm in Java

1 /** Computes shortest-path distances from src vertex to all reachable vertices of g. */ 2 public static <V> Map<Vertex<V>, Integer> 3 shortestPathLengths(Graph<V,Integer> g, Vertex<V> src) { 4 // d.get(v) is upper bound on distance from src to v 5 Map<Vertex<V>, Integer> d = new ProbeHashMap<>( ); 6 // map reachable v to its d value 7 Map<Vertex<V>, Integer> cloud = new ProbeHashMap<>( ); 8 // pq will have vertices as elements, with d.get(v) as key 9 AdaptablePriorityQueue<Integer, Vertex<V>> pq; 10 pq = new HeapAdaptablePriorityQueue<>( ); 11 // maps from vertex to its pq locator 12 Map<Vertex<V>, Entry<Integer,Vertex<V>>> pqTokens; 13 pqTokens = new ProbeHashMap<>( ); 14 15 // for each vertex v of the graph, add an entry to the priority queue, with 16 // the source having distance 0 and all others having infinite distance 17 for (Vertex<V> v : g.vertices( )) { 18 if (v == src) 19 d.put(v,0); 20 else 21 d.put(v, Integer.MAX VALUE); 22 pqTokens.put(v, pq.insert(d.get(v), v)); // save entry for future updates 23 }

Let G be a graph. Then the following statements are equivalent:

1) G is a tree 2) G is connected and acyclic 3) Between any two vertices of G there is precisouly one path

java for dijkstra algorithm

24 // now begin adding reachable vertices to the cloud 25 while (!pq.isEmpty( )) { 26 Entry<Integer, Vertex<V>> entry = pq.removeMin( ); 27 int key = entry.getKey( ); 28 Vertex<V> u = entry.getValue( ); 29 cloud.put(u, key); // this is actual distance to u 30 pqTokens.remove(u); // u is no longer in pq 31 for (Edge<Integer> e : g.outgoingEdges(u)) { 32 Vertex<V> v = g.opposite(u,e); 33 if (cloud.get(v) == null) { 34 // perform relaxation step on edge (u,v) 35 int wgt = e.getElement( ); 36 if (d.get(u) + wgt < d.get(v)) { // better path to v? 37 d.put(v, d.get(u) + wgt); // update the distance 38 pq.replaceKey(pqTokens.get(v), d.get(v)); // update the pq entry 39 } 40 } 41 } 42 } 43 return cloud; // this only includes reachable vertices 44}

Tree

A connected graph that contains no circuits.

Weighted Graph

A graph G(V, E) together with a function w: [0, infinity). If e is an edge the nonnegative real number w(e) is called the weight of e. The weight of a subgraph of G (often a path or a trail) is the sum of the weights of the edges of the subgraph.

Spanning Tree

A spanning tree of a connected graph G is a subgraph that is a tree and that includes every vertex of G. A minimum spanning tree of a weigthed graph is a spanning tree of least weight, that is, a spanning tree for which the sum of the weights of all its edges os least among all the spanning trees

Rooted

A tree is rooted if it comes with a specified vertex, called the root

Leaf

A vertex of degree 1.

Algorithm Description and Example

Algorithm ShortestPath(G, s): Input: A directed or undirected graph G with nonnegative edge weights, and a distinguished vertex s of G. Output: The length of a shortest path from s to v for each vertex v of G. Initialize D[s] = 0 and D[v] = ∞for each vertex v 6= s. Let a priority queue Q contain all the vertices of G using the D labels as keys. while Q is not empty do {pull a new vertex u into the cloud} u = value returned by Q.removeMin( ) for each edge (u,v) such that v is in Q do {perform the relaxation procedure on edge (u,v)} if D[u]+w(u,v) < D[v] then D[v] = D[u]+w(u,v) Change the key of vertex v in Q to D[v]. return the label D[v] of each vertex v

How to solve an unweighted shortest path problem?

An unweighted shortest path problem can be solved by treating all edges as having weight = 1. Therefore, it can be solved as a special case of the weighted shortest path problem.

D Step 3

Choose the least of all temporary labels on the network. Make this label permanent by boxing it.

D Step 2

Consider the node with the most recently boxed label. Suppose this node to be X and let D be its permanent label. Then, in turn, consider each node directly joined to X but not yet permanently boxed. For each node, Y say, temporarily label it with the lesser of D+(the weight of arc XY) and its existing label (if any.)

What is the algorithm for the unweighted shortest path problem?

Determine distances from a vertex by starting with the vertex and finding all adjacent vertices (these have length 1). Move to each of the adjacent vertices and find all of their adjacent vertices not already visited. These have length 2. Continue until all vertices are visited. (BREADTH-FIRST SEARCH)

All-pairs shortest path

Dijkstra - O(n^3) Floyd-Warshall - θ(n^3) - Slightly better in practice because tight loops

Algorithm that cannot use negative edge weights

Dijkstra's

What is a single-source shortest path problem?

Fine the shortest weighted path from a vertex, s, to every other vertex in the graph.

D Step 5

Go backwards through the network, retracing the path of shortest length from the destination node to the start node.

The Running Time of Dijkstra's Algorithm

In this section, we analyze the time complexity of Dijkstra's algorithm. We denote with n and m the number of vertices and edges of the input graph G, respectively. We assume that the edge weights can be added and compared in constant time. Because of the high level of the description we gave for Dijkstra's algorithm in Code Fragment 14.12, analyzing its running time requires that we give more details on its implementation. Specifically, we should indicate the data structures used and how they are implemented

short path algorithm

It is probably not immediately clear why Dijkstra's algorithm correctly finds the shortest path from the start vertex s to each other vertex u in the graph. Why is it that the distance from s to u is equal to the value of the label D[u] at the time vertex u is removed from the priority queue Q and added to the cloud C? The answer to this question depends on there being no negative-weight edges in the graph, for it allows the greedy method to work correctly, as we show in the proposition that follows.

How is the shortest path table set up?

Known is set to true after a vertex is processed, dv is distance from v3, start all vertices at infinite distance except first one (0), pv is the previous vertex used to reach this vertex

Prim vs Kruskal on sparse graphs

Kruskal is faster

D Step 1

Label the start node with zero and box this label.

Kirchhof's Theorem

Let M be the matrix obtained from the adjacency matrix of a connected graph G by changing all 1's to -1's and each diagonal 0 to the degree of the corresponding vertex. Then the number of spanning trees of G is the value of any cofactor of M.

Edge Relaxation

Let us define a label D[v] for each vertex v in V, which we use to approximate the distance in G from s to v. The meaning of these labels is that D[v] will always store the length of the best path we have found so far from s to v. Initially, D[s] = 0 and D[v] =∞for each v 6= s, and we define the set C, which is our "cloud" of vertices, to initially be the empty set. At each iteration of the algorithm, we select a vertex u not in C with smallest D[u] label, and we pull u into C. (In general, we will use a priority queue to select among the vertices outside the cloud.) In the very first iteration we will, of course, pull s into C. Once a new vertex u is pulled into C, we update the label D[v] of each vertex v that is adjacent to u and is outside of C, to reflect the fact that there may be a new and better way to get to v via u. This update operation is known as a relaxation procedure, for it takes an old estimate and checks if it can be improved to get closer to its true value. The specific edge relaxation operation is as follows: Edge Relaxation: if D[u]+w(u,v) < D[v] then D[v] = D[u]+w(u,v

Algorithm unaffected by negative edge weights

MST

Better Dijkstra (Sparse graphs)

O(m log n) -heap of vertices

Prim/Dijkstra Running time

O(n^2) -adjacency lists

D Step 4

Repeat Steps 2 and 3 until the destination node has a permanent label.

Dijkstra's Algorithm

Solution to the single-source shortest path problem in graph theory ¤ Both directed and undirected graphs ¤ All edges must have nonnegative weights ¤ Graph must be connected

In Dijkstra's algorithm, whenever a vertex v is pulled into the cloud, the label D[v] is equal to d(s,v), the length of a shortest path from s to v.

Suppose that D[v] > d(s,v) for some vertex v in V, and let z be the first vertex the algorithm pulled into the cloud C (that is, removed from Q) such that D[z] > d(s, z). There is a shortest path P from s to z (for otherwise d(s, z) = ∞ = D[z]). Let us therefore consider the moment when z is pulled into C, and let y be the first vertex of P (when going from s to z) that is not in C at this moment. Let x be the predecessor of y in path P (note that we could have x = s). (See Figure 14.18.) We know, by our choice of y, that x is already in C at this point.

main ides of algorith in greedy algorithms

The algorithm terminates when no more vertices are outside the cloud (or when those outside the cloud are not connected to those within the cloud), at which point we have a shortest path from s to every vertex of G that is reachable from s. This approach is a simple, but nevertheless powerful, example of the greedy-method design pattern. Applying the greedy method to the single-source, shortest-path problem, results in an algorithm known as Dijkstra's algorithm

Why It Works

The interesting aspect of the Dijkstra algorithm is that, at the moment a vertex u is pulled into C, its label D[u] stores the correct length of a shortest path from v to u. Thus, when the algorithm terminates, it will have computed the shortest-path distance from s to every vertex of G. That is, it will have solved the single-source shortest-path problem

main idea in apply greedy method

The main idea in applying the greedy-method pattern to the single-source shortestpath problem is to perform a "weighted" breadth-first search starting at the sourcevertex s.

What is an unweighted path length?

The number of edges in the path, N-1

Theorem 12.2.3

The number of labeled trees with n>=3 vertices is n^(n-2).

What is a weighted path length?

The sum of the weights on the path.

Isomorphic

Trees T1 and T2 whose vertices are labeled with the same set of labels are isomorphic if and only if, for each pair of labels v and w, vertices v and w are adjacent in T1, if and only if they are adjaent in T2

How do we write code for the unweighted shortest path problem?

Use a table to keep track of each vertex as it is visited.

Floyd-Warshall Algorithm

Used to find the shortest distance between all pairs of vertices in a weighted graph where the are v1, v2,..., vn.

Dijkstra's Algorithm

Used to the find the shortest path from vertex A to vertex E in a weighted graph.

How can shortest path be used to model planes?

Vertices represent airplanes or other traffic routes, the shortest path represents the best route between two points.

How can shortest path be used to model computer communication costs?

Vertices represent computers, edges represent links, weights represent communication costs. Shortest path is the cheapest route.

convergence property

if there is a shortest path from source to A and we relax from A to B(it is better to go to B through A) then there is a shortest path from source to B

predecessor-subgraph property

if there is a shortest path to a node then all previous have shortest path too

no-path property

if there is no path it will be infinity duuh

path-relaxation property

if we relax all pairs from each other then in the end we have a shortest path through them

Triangle inequality

shortest distance between A and B D(A,B) is not greater than D(A,C) + D(C,B) for any other vertex C not lying in the shortest path from A to B.

upper-bound property

the distance to v >= shortest path from source to v, but when it reaches the shortest path it never changes, duuuh

development of greedy method

we can use the greedy method to develop an algorithm that iteratively grows a "cloud" of vertices out of s, with the vertices entering the cloud in order of their distances froms


Related study sets

Chapter 11: The Healthcare Delivery System

View Set

Chapter 48: Assessment and Management of Patients with Obesity

View Set

ΒΙΟΛΟΓΙΑ -1ο Κεφάλαιο β( Κύτταρο : η μονάδα της ζωής)

View Set

ふつうの人がイメージできる花 Names of flowers(1/2)

View Set

Changing mixed numbers into improper fractions

View Set