3 Unweighted Directed Graphs V1V2 V3V4 V5 V6V7 What is the shortest path from V3 to V5?
4 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
5 Example Adjacency lists : V1: V2, V4 V2: V4, V5 V3: V1, V6 V4: V3, V5, V6, V7 V5: V7 V6: - V7: V6 Let s = V3, stored in a queue Initialized distance table: distance parent V V V3 0 0 V V V V
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 1.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
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 V1V2 V3V4 V5 V6V7 What is the shortest distance from V3 to V7?
10 Comparison Similar to the algorithm for unweighted graphs Differences: weights - weights are included in the graph representation priority queue - priority queue : the node with the smallest distance is chosen for processing sum of weights - distance is not any more the number of edges, instead it is the sum of weights updated - Distance table is updated if newly computed distance is smaller.
11 Algorithm s distance = 0 1. Store s in a priority queue with distance = 0 2. While there are vertices in the queue DeleteMin v DeleteMin a vertex v from the queue w For all adjacent vertices w : Compute new distance Store in / update Distance table Insert/update in priority queue
12 Processing Adjacent Nodes w: 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
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