{"id":26687,"date":"2017-12-22T20:28:19","date_gmt":"2017-12-22T14:58:19","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26687"},"modified":"2017-12-22T20:28:19","modified_gmt":"2017-12-22T14:58:19","slug":"shortest-path-directed-acyclic-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/shortest-path-directed-acyclic-graph\/","title":{"rendered":"Python Algorithm-Shortest Path-Shortest Path in Directed Acyclic Graph"},"content":{"rendered":"<p>Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices.<span id=\"more-117750\"><\/span><br \/>\nFor a general weighted graph, we can calculate single source shortest distances in O(VE) time using <a href=\"http:\/\/www.geeksforgeeks.org\/dynamic-programming-set-23-bellman-ford-algorithm\/\" target=\"_blank\" rel=\"noopener noreferrer\">Bellman\u2013Ford Algorithm<\/a>. For a graph with no negative weights, we can do better and calculate single source shortest distances in O(E + VLogV) time using <a href=\"http:\/\/www.geeksforgeeks.org\/greedy-algorithms-set-7-dijkstras-algorithm-for-adjacency-list-representation\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dijkstra\u2019s algorithm<\/a>. Can we do even better for Directed Acyclic Graph (DAG)? We can calculate single source shortest distances in O(V+E) time for DAGs. The idea is to use <a href=\"http:\/\/www.geeksforgeeks.org\/topological-sorting\/\" target=\"_blank\" rel=\"noopener noreferrer\">Topological Sorting<\/a>.<\/p>\n<p>We initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph. <a href=\"http:\/\/www.geeksforgeeks.org\/topological-sorting\/\" target=\"_blank\" rel=\"noopener noreferrer\">Topological Sorting<\/a> of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following figure is taken from <a href=\"http:\/\/www.utdallas.edu\/~sizheng\/CS4349.d\/l-notes.d\/L17.pdf\" target=\"_blank\" rel=\"noopener\">this <\/a>source. It shows step by step process of finding shortest paths.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26696\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph.png\" alt=\"Shortest Path-Shortest Path in Directed Acyclic Graph\" width=\"996\" height=\"967\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph.png 996w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph-300x291.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph-768x746.png 768w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph-990x961.png 990w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-Path-Shortest-Path-in-Directed-Acyclic-Graph-434x420.png 434w\" sizes=\"(max-width: 996px) 100vw, 996px\" \/><strong>Following is complete algorithm for finding shortest distances.<\/strong><br \/>\n<strong>1)<\/strong> Initialize dist[] = {INF, INF, \u2026.} and dist[s] = 0 where s is the source vertex.<br \/>\n<strong>2)<\/strong> Create a toplogical order of all vertices.<br \/>\n<strong>3) <\/strong>Do following for every vertex u in topological order.<br \/>\nDo following for every adjacent vertex v of u<br \/>\nif (dist[v] &gt; dist[u] + weight(u, v))<br \/>\ndist[v] = dist[u] + weight(u, v)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Python Programming<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to find single source shortest paths<br\/># for Directed Acyclic Graphs Complexity :OV(V+E)<br\/>from collections import defaultdict<br\/> <br\/># Graph is represented using adjacency list. Every<br\/># node of adjacency list contains vertex number of<br\/># the vertex to which edge connects. It also contains<br\/># weight of the edge<br\/>class Graph:<br\/>    def __init__(self,vertices):<br\/> <br\/>        self.V = vertices # No. of vertices<br\/> <br\/>        # dictionary containing adjacency List<br\/>        self.graph = defaultdict(list)<br\/> <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v,w):<br\/>        self.graph[u].append((v,w))<br\/> <br\/> <br\/>    # A recursive function used by shortestPath<br\/>    def topologicalSortUtil(self,v,visited,stack):<br\/> <br\/>        # Mark the current node as visited.<br\/>        visited[v] = True<br\/> <br\/>        # Recur for all the vertices adjacent to this vertex<br\/>        if v in self.graph.keys():<br\/>            for node,weight in self.graph[v]:<br\/>                if visited[node] == False:<br\/>                    self.topologicalSortUtil(node,visited,stack)<br\/> <br\/>        # Push current vertex to stack which stores topological sort<br\/>        stack.append(v)<br\/> <br\/> <br\/>    &#039;&#039;&#039; The function to find shortest paths from given vertex.<br\/>        It uses recursive topologicalSortUtil() to get topological<br\/>        sorting of given graph.&#039;&#039;&#039;<br\/>    def shortestPath(self, s):<br\/> <br\/>        # Mark all the vertices as not visited<br\/>        visited = [False]*self.V<br\/>        stack =[]<br\/> <br\/>        # Call the recursive helper function to store Topological<br\/>        # Sort starting from source vertice<br\/>        for i in range(self.V):<br\/>            if visited[i] == False:<br\/>                self.topologicalSortUtil(s,visited,stack)<br\/> <br\/>        # Initialize distances to all vertices as infinite and<br\/>        # distance to source as 0<br\/>        dist = [float(&quot;Inf&quot;)] * (self.V)<br\/>        dist[s] = 0<br\/> <br\/>        # Process vertices in topological order<br\/>        while stack:<br\/> <br\/>            # Get the next vertex from topological order<br\/>            i = stack.pop()<br\/> <br\/>            # Update distances of all adjacent vertices<br\/>            for node,weight in self.graph[i]:<br\/>                if dist[node] &gt; dist[i] + weight:<br\/>                    dist[node] = dist[i] + weight<br\/> <br\/>        # Print the calculated shortest distances<br\/>        for i in range(self.V):<br\/>            print (&quot;%d&quot; %dist[i]) if dist[i] != float(&quot;Inf&quot;) else  &quot;Inf&quot; ,<br\/> <br\/> <br\/>g = Graph(6)<br\/>g.addEdge(0, 1, 5)<br\/>g.addEdge(0, 2, 3)<br\/>g.addEdge(1, 3, 6)<br\/>g.addEdge(1, 2, 2)<br\/>g.addEdge(2, 4, 4)<br\/>g.addEdge(2, 5, 2)<br\/>g.addEdge(2, 3, 7)<br\/>g.addEdge(3, 4, -1)<br\/>g.addEdge(4, 5, -2)<br\/> <br\/># source = 1<br\/>s = 1<br\/> <br\/>print (&quot;Following are shortest distances from source %d &quot; % s)<br\/>g.shortestPath(s)<\/code><\/pre> <\/div>\n<p>&nbsp;<\/p>\n<p>Output:<\/p>\n<pre>Following are shortest distances from source 1\r\nINF 0 2 6 5 3<\/pre>\n<p><strong>Time Complexity:<\/strong> Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>shortest path directed acyclic graph<br \/>\nGiven a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest path<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,4148],"tags":[83668,83672,83670,83664,83671,83667,83669,83665,83673,83666,79910,83675,83674],"class_list":["post-26687","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-python","tag-c-code-for-directed-acyclic-graph","tag-dag-shortest-path-algorithm","tag-dag-shortest-path-vs-dijkstra","tag-directed-acyclic-graph-algorithm","tag-directed-acyclic-graph-topological-sort","tag-directed-acyclic-graph-tutorial","tag-shortest-path-algorithm-in-data-structure","tag-shortest-path-dag-dynamic-programming","tag-shortest-path-dag-negative-weights","tag-shortest-path-directed-graph","tag-shortest-path-in-graph","tag-shortest-path-problem-example","tag-single-source-shortest-path-problem"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26687","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26687"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26687\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26687"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26687"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26687"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}