Presentation on theme: "Chapter 9: Graphs Shortest Paths"— Presentation transcript:
1 Chapter 9: Graphs Shortest Paths Mark Allen Weiss: Data Structures and Algorithm Analysis in JavaChapter 9: GraphsShortest PathsLydia Sinapova, Simpson College
2 Shortest Paths Shortest Paths in Unweighted Graphs Shortest Paths in Weighted Graphs - Dijkstra’s AlgorithmAnimation
3 Unweighted Directed Graphs V1V2V3V4V5V6V7What is the shortest path from V3 to V5?
4 Problem DataThe problem: Given a source vertex s, find the shortest path to all other vertices.Data structures needed:Graph representation:Adjacency lists / adjacency matrixDistance table:distances from source vertexpaths from source vertex
5 Example Let s = V3, stored in a queue Initialized distance table: distance parentVVVVVVVAdjacency lists :V1: V2, V4V2: V4, V5V3: V1, V6V4: V3, V5, V6, V7V5: V7V6: -V7: V6
6 Breadth-first search in graphs Take a vertex and examine all adjacent vertices.Do the same with each of the adjacent vertices .
7 Algorithm Store s in a queue, and initialize distance = 0 in the Distance Table2. While there are vertices in the queue:Read a vertex v from the queue For all adjacent vertices w :If distance = -1 (not computed)Distance = (distance to v) + 1Parent = vAppend w to the queue
8 Complexity Matrix representation: O(|V|2) Adjacency lists - O(|E| + |V|)We examine all edges (O(|E|)), and we store in the queue each vertex only once (O(|V|)).
9 Weighted Directed Graphs V1V2V3V4V5V6V7What is the shortest distance from V3 to V7?
10 Comparison Differences: Similar to the algorithm for unweighted graphsDifferences:weights are included in the graph representationpriority queue : the node with the smallest distance is chosen for processingdistance is not any more the number of edges, instead it is the sum of weightsDistance table is updated if newly computed distance is smaller.
11 Algorithm 1. Store s in a priority queue with distance = 0 2. While there are vertices in the queueDeleteMin a vertex v from the queueFor all adjacent vertices w:Compute new distanceStore in / update Distance tableInsert/update in priority queue
12 Processing Adjacent Nodes For all adjacent vertices w:Compute new distance = (distance to v) + (d(v,w))If distance = -1 (not computed)store new distance in tablepath = vInsert w in priority queueIf old distance > new distanceUpdate old_distance = new_distanceUpdate path = vUpdate priority in priority queue
13 Complexity O(E logV + V logV) = O((E + V) log(V)) Each vertex is stored only once in the queue – O(V)DeleteMin operation is : O( V logV )Updating the priority queue –search and inseart: O(log V)performed at most for each edge: O(E logV)
14 Historical Notes Invented by Edsger Dijkstra in 1955