Graphs 3 Adapted From: Data Structures and Their Algorithms, by Harry R. Lewis and Larry Denenberg (Harvard University: Harper Collins Publishers) Data Structures and Algorithms 1
Analysis of Dijkstra’s Least Cost Paths Algorithm Data Structures and Algorithms 2
Given directed graph G and start vertex S Part 1 of Dijkstra make an empty set U for each vertex v in G do dist(v) = infinity insert v into U dist(S) = 0 Data Structures and Algorithms 3
Part 2 of Dijkstra repeat |G| times v = any member of U with minimum distance delete v from U for each neighbor w of v do if w is a member of U do dist(w) = min(dist(w), dist(v) + cost(v, w)) Data Structures and Algorithms 4
Two Implementatations • Adjacency Matrix a matrix is used to hold the costs an array of boolean implements the set U an array of ints holds the distance values • Adjacency list An array of lists holds the graph Use a heap to hold the set U Data Structures and Algorithms 5
Two Implementatations • Adjacency Matrix search costs (n) each iteration of the main loop consists of one search and at most n-1 updates of distance fields the total time is (n 2) • Adjacency list An array of lists holds the graph Use a heap to hold the set U Data Structures and Algorithms 6
• Adjacency list time to initialize U (n) n deletemin operations O(n * lg n) modify distance in heap for every edge in the graph O(e Lg n) Overall : O((n + e) lg n) Data Structures and Algorithms 7
Which is better? For dense graphs e is about n 2 which makes the adjacency matrix representation better. For sparse graphs, e is small so choose the heap implementation. Data Structures and Algorithms 8