Dijkstra's algorithm Shortest paths in edge-weighted digraph Krasin Georgiev Assistant Professor Technical University of Sofia g.krasin at gmail com Table of Contents 1. Background 2. The problem 3. Properties and assumptions 4. Applications 5. Dijkstra's algorithm and Pseudocode 6. C# Demo 7. Related problems and algorithms 8. Resources 2 Background Let G=(V,E) be a (di)graph. In directed graphs, edges are one-way An edge-weighted graph is a graph where we associate weights or costs with each edge (or other attributes). A shortest path from vertex s to vertex t is a directed path from s to t with the property that no other such path has a lower weight. 3 The Problem Single-Source Shortest Path Problem Find the shortest paths from a source vertex to all other vertices in the graph 4 Properties and Assumptions Paths are directed. The weights are not necessarily distances (could be time or cost). Edge weights are positive (or zero) Shortest paths are not necessarily unique Not all vertices need be reachable Parallel edges may be present 5 Algorithm Applications Application Vertex Edge Solutions Map Intersection Road Find the shortest route Find the fastest route Find the best route Network Router Connection Internet routing Flight Agenda Airports Flights Find earliest time to reach destination Epidemiology Individuals Possible contacts Model the spread of infectious diseases Arbitrage Exchange rate Currency 6 Algorithm Description Dijkstra's algorithm first initiates all vertex distances with preliminary values and puts all vertexes in a priority queue. Then picks the unvisited vertex with the lowest-distance, calculates the distance through it to each unvisited neighbor, and updates the neighbor's distance if smaller. Mark visited when done with neighbors. 7 Algorithm Trace Trough 8 Algorithm Trace Trough 9 Algorithm Pseudocode function Dijkstra(Graph, source): for each vertex v in Graph: dist[v] := infinity ; previous[v] := undefined ; end for dist[source] := 0 ; Q := the set of all nodes in Graph ; while Q is not empty: u := vertex in Q with smallest distance in dist[] ; remove u from Q ; if dist[u] = infinity: break ; end if for each neighbor v of u in Q: alt := dist[u] + dist_between(u, v) ; if alt < dist[v]: dist[v] := alt ; previous[v] := u ; decrease-key v in Q; end if end for end while return dist; // // // // // Initializations Unknown distance function from source to v Previous node in optimal path from source // // // // // Distance from source to source All nodes in the graph are put in a Priority Queue Q The main loop Start node in first case // all remaining vertices are // inaccessible from source // where v has not yet been // removed from Q. // Relax (u,v,a) // Reorder v in the Queue 10 C# Demo 0 6 3 1 5 4 2 Modifications We can solve different problems using modified Dijkstra algorithm elements: Graph –vertices, edges and weights meanings Distance – definition Priority Queue Relaxation and Distance Initialization 12 Some Theory Dijkstra algorithm is based on the following Lemmas: Shortest paths are composed of shortest paths. It is based on the fact that if there was a shorter path than any sub-path, then the shorter path should replace that sub-path to make the whole path shorter. The sum of the lengths of any two sides of a triangle is greater than the length of the third side. 13 Some Theory Analysis of Dijkstra’s Algorithm: The initialization uses only O(n) time. Each vertex is processed exactly once. The inner loop is called once for each edge in the graph. Each call of the inner loop does O(1) work plus, possibly, one Decrease-Key operation. All of the priority queue operations require time Finally and we get time If unsorted sequence is used instead of priority queue we get O(n2 + e) 14 Related algorithms Breadth-first search - special-case of Dijkstra's algorithm on unweighted graphs when all edge costs are positive and identical. The priority queue degenerates into a FIFO queue. Uniform-cost search - the shortest path to a particular node The A* algorithm - generalization of Dijkstra's algorithm that cuts down on the size of the subgraph that must be explored, if additional information is available that provides a lower bound on the "distance" to the target. 15 Resources http://algs4.cs.princeton.edu/44sp/ http://en.wikipedia.org/wiki/Dijkstra%27s_alg orithm http://ocw.mit.edu/OcwWeb/Electrical- Engineering-and-Computer-Science/6046JFall-2005/CourseHome/ https://www.udacity.com/course/cs271 Nakov’s book: Programming = ++Algorithms; 16 Dijkstra's algorithm курсове и уроци по програмиране, уеб дизайн – безплатно курсове и уроци по програмиране – Телерик академия уроци по програмиране и уеб дизайн за ученици програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки курсове и уроци по програмиране, книги – безплатно от Наков уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop free C# book, безплатна книга C#, книга Java, книга C# безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge форум програмиране, форум уеб дизайн ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC алго академия – състезателно програмиране, състезания курс мобилни приложения с iPhone, Android, WP7, PhoneGap Дончо Минков - сайт за програмиране Николай Костов - блог за програмиране C# курс, програмиране, безплатно http://algoacademy.telerik.com Free Trainings @ Telerik Academy “C# Programming @ Telerik Academy Telerik Software Academy academy.telerik.com Telerik Academy @ Facebook csharpfundamentals.telerik.com facebook.com/TelerikAcademy Telerik Software Academy Forums forums.academy.telerik.com