Download presentation
Presentation is loading. Please wait.
Published byHaden Hosken Modified over 9 years ago
1
The Greedy Approach Chapter 8
2
The Greedy Approach It’s a design technique for solving optimization problems Based on finding optimal local solutions which may lead to optimal global one. Walk slowly but surely. At each step choose the best choice & hopefully it will be part of the optimal global solution.
3
The Single-source Shortest Path Problem Section 8.2
4
Problem Let G=(V,E) be a directed weighted graph where each edge has a length 0. Let s V be a certain vertex called the source. For simplicity, let V={1,2,..,n}, s=1 Find all [u] =distance from s to any vertex u.
5
Dijkstra’s Solution Divide V into two disjoint sets X and Y where X contains all vertices whose distances from 1have been already determined. So X={1} initially At each step, choose y Y whose [y] is min where [y]= length of shortest path from 1 to y walking through X only. 1 X Y y [y]
6
Dijkstra’s Solution Move y to X and remove it from Y Update [w], for all w Y that is adjacent to y. Claim: when y is moved to X then [y] = [y] y Y X
7
Algorithm: Dijkstra Input: weighted graph G=(V,E) Output: distances from 1 to every vertex X {1}; Y V - {1}; [1] 0 For y 2 to n if y is adjacent to 1 then [y] length[1,y] else [1] end for for i 1 to n-1 let y be the vertex with min [y] in Y X X {y}; Y Y-{y} for each edge (y,w) z [y] +length[y,w] if (w Y and z < [w]) then [w] z end for
8
Analysis Time = (m + n 2 ) = (n 2 ), where m is the number of edges. Notice that finding the min [y] costs (n) time
9
Implementation The graph G should be saved as adjacency list. Costs (m + n) space, where m is the number of edges Use binary arrays to represent the sets X and Y. Notice that Y= X c
10
Correction When a vertex y is moved to the set X and [y] is finite then [y] = [y]
11
Improving Dijkstra The time can be improved to (m log n) if m=o(n 2 /log n) by using min-heap to find the min [y]. Notice that updating the heap takes O(log n) time there could be at most m updates.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.