 # Chapter 9: Graphs Shortest Paths

## Presentation on theme: "Chapter 9: Graphs Shortest Paths"— Presentation transcript:

Chapter 9: Graphs Shortest Paths
Mark Allen Weiss: Data Structures and Algorithm Analysis in Java Chapter 9: Graphs Shortest Paths Lydia Sinapova, Simpson College

Shortest Paths Shortest Paths in Unweighted Graphs
Shortest Paths in Weighted Graphs - Dijkstra’s Algorithm Animation

Unweighted Directed Graphs
V1 V2 V3 V4 V5 V6 V7 What is the shortest path from V3 to V5?

Problem Data The problem: Given a source vertex s, find the shortest path to all other vertices. Data structures needed: Graph representation: Adjacency lists / adjacency matrix Distance table: distances from source vertex paths from source vertex

Example Let s = V3, stored in a queue Initialized distance table:
distance parent V V V V V V V Adjacency lists : V1: V2, V4 V2: V4, V5 V3: V1, V6 V4: V3, V5, V6, V7 V5: V7 V6: - V7: V6

Take a vertex and examine all adjacent vertices. Do the same with each of the adjacent vertices .

Algorithm Store s in a queue, and initialize
distance = 0 in the Distance Table 2. 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) + 1 Parent = v Append w to the queue

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|)).

Weighted Directed Graphs
V1 V2 V3 V4 V5 V6 V7 What is the shortest distance from V3 to V7?

Comparison Differences:
Similar to the algorithm for unweighted graphs Differences: weights are included in the graph representation priority queue : the node with the smallest distance is chosen for processing distance is not any more the number of edges, instead it is the sum of weights Distance table is updated if newly computed distance is smaller.

Algorithm 1. Store s in a priority queue with distance = 0
2. While there are vertices in the queue DeleteMin a vertex v from the queue For all adjacent vertices w: Compute new distance Store in / update Distance table Insert/update in priority queue

For all adjacent vertices w: Compute new distance = (distance to v) + (d(v,w)) If distance = -1 (not computed) store new distance in table path = v Insert w in priority queue If old distance > new distance Update old_distance = new_distance Update path = v Update priority in priority queue

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)

Historical Notes Invented by Edsger Dijkstra in 1955