{"id":26783,"date":"2017-12-24T15:22:53","date_gmt":"2017-12-24T09:52:53","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26783"},"modified":"2017-12-24T15:22:53","modified_gmt":"2017-12-24T09:52:53","slug":"shortest-path-exactly-k-edges-directed-weighted-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/shortest-path-exactly-k-edges-directed-weighted-graph\/","title":{"rendered":"Java Programming-Shortest path with exactly k edges in a directed and weighted graph"},"content":{"rendered":"<p>Given a directed and two vertices \u2018u\u2019 and \u2018v\u2019 in it, find shortest path from \u2018u\u2019 to \u2018v\u2019 with exactly k edges on the path.<span id=\"more-130858\"><\/span><\/p>\n<p>The graph is given as <a href=\"http:\/\/www.geeksforgeeks.org\/graph-and-its-representations\/\" target=\"_blank\" rel=\"noopener noreferrer\">adjacency matrix representation<\/a> where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j.<\/p>\n<p>For example consider the following graph. Let source \u2018u\u2019 be vertex 0, destination \u2018v\u2019 be 3 and k be 2. There are two walks of length 2, the walks are {0, 2, 3} and {0, 1, 3}. The shortest among the two is {0, 2, 3} and weight of path is 3+6 = 9.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26791\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Shortest-path-with-exactly-k-edges-in-a-directed-and-weighted-graph.png\" alt=\"Shortest path with exactly k edges in a directed and weighted graph\" width=\"300\" height=\"203\" \/><\/p>\n<p>The idea is to browse through all paths of length k from u to v using the approach discussed in the <a href=\"http:\/\/www.geeksforgeeks.org\/count-possible-paths-source-destination-exactly-k-edges\/\" target=\"_blank\" rel=\"noopener noreferrer\">previous post<\/a> and return weight of the shortest path. A <strong>simple solution<\/strong> is to start from u, go to all adjacent vertices and recur for adjacent vertices with k as k-1, source as adjacent vertex and destination as v. Following are C++ and Java implementations of this simple solution.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java Programming<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Dynamic Programming based Java program to find shortest path<br\/>\/\/ with exactly k edges<br\/>import java.util.*;<br\/>import java.lang.*;<br\/>import java.io.*;<br\/> <br\/>class ShortestPath<br\/>{<br\/>    \/\/ Define number of vertices in the graph and inifinite value<br\/>    static final int V = 4;<br\/>    static final int INF = Integer.MAX_VALUE;<br\/> <br\/>    \/\/ A naive recursive function to count walks from u to v<br\/>    \/\/ with k edges<br\/>    int shortestPath(int graph[][], int u, int v, int k)<br\/>    {<br\/>        \/\/ Base cases<br\/>        if (k == 0 &amp;&amp; u == v)             return 0;<br\/>        if (k == 1 &amp;&amp; graph[u][v] != INF) return graph[u][v];<br\/>        if (k &lt;= 0)                       return INF;<br\/> <br\/>        \/\/ Initialize result<br\/>        int res = INF;<br\/> <br\/>        \/\/ Go to all adjacents of u and recur<br\/>        for (int i = 0; i &lt; V; i++)<br\/>        {<br\/>            if (graph[u][i] != INF &amp;&amp; u != i &amp;&amp; v != i)<br\/>            {<br\/>                int rec_res = shortestPath(graph, i, v, k-1);<br\/>                if (rec_res != INF)<br\/>                    res = Math.min(res, graph[u][i] + rec_res);<br\/>            }<br\/>        }<br\/>        return res;<br\/>    }<br\/> <br\/>    public static void main (String[] args)<br\/>    {<br\/>        \/* Let us create the graph shown in above diagram*\/<br\/>        int graph[][] = new int[][]{ {0, 10, 3, 2},<br\/>                                     {INF, 0, INF, 7},<br\/>                                     {INF, INF, 0, 6},<br\/>                                     {INF, INF, INF, 0}<br\/>                                   };<br\/>        ShortestPath t = new ShortestPath();<br\/>        int u = 0, v = 3, k = 2;<br\/>        System.out.println(&quot;Weight of the shortest path is &quot;+<br\/>                           t.shortestPath(graph, u, v, k));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Weight of the shortest path is 9<\/pre>\n<p>The worst case time complexity of the above function is O(V<sup>k<\/sup>) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing recursion tree. The worst occurs for a complete graph. In worst case, every internal node of recursion tree would have exactly V children.<br \/>\nWe can optimize the above solution using <strong><a href=\"http:\/\/www.geeksforgeeks.org\/dynamic-programming-set-1\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dynamic Programming<\/a><\/strong>. The idea is to build a 3D table where first dimension is source, second dimension is destination, third dimension is number of edges from source to destination, and the value is count of walks. Like other <a href=\"http:\/\/www.geeksforgeeks.org\/tag\/dynamic-programming\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dynamic Programming problems<\/a>, we fill the 3D table in bottom up manner.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java programming<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Dynamic Programming based Java program to find shortest path with<br\/>\/\/ exactly k edges<br\/>import java.util.*;<br\/>import java.lang.*;<br\/>import java.io.*;<br\/> <br\/>class ShortestPath<br\/>{<br\/>    \/\/ Define number of vertices in the graph and inifinite value<br\/>    static final int V = 4;<br\/>    static final int INF = Integer.MAX_VALUE;<br\/> <br\/>    \/\/ A Dynamic programming based function to find the shortest path<br\/>    \/\/ from u to v with exactly k edges.<br\/>    int shortestPath(int graph[][], int u, int v, int k)<br\/>    {<br\/>        \/\/ Table to be filled up using DP. The value sp[i][j][e] will<br\/>        \/\/ store weight of the shortest path from i to j with exactly<br\/>        \/\/ k edges<br\/>        int sp[][][] = new int[V][V][k+1];<br\/> <br\/>        \/\/ Loop for number of edges from 0 to k<br\/>        for (int e = 0; e &lt;= k; e++)<br\/>        {<br\/>            for (int i = 0; i &lt; V; i++)  \/\/ for source<br\/>            {<br\/>                for (int j = 0; j &lt; V; j++) \/\/ for destination<br\/>                {<br\/>                    \/\/ initialize value<br\/>                    sp[i][j][e] = INF;<br\/> <br\/>                    \/\/ from base cases<br\/>                    if (e == 0 &amp;&amp; i == j)<br\/>                        sp[i][j][e] = 0;<br\/>                    if (e == 1 &amp;&amp; graph[i][j] != INF)<br\/>                        sp[i][j][e] = graph[i][j];<br\/> <br\/>                    \/\/ go to adjacent only when number of edges is<br\/>                    \/\/ more than 1<br\/>                    if (e &gt; 1)<br\/>                    {<br\/>                        for (int a = 0; a &lt; V; a++)<br\/>                        {<br\/>                            \/\/ There should be an edge from i to a and<br\/>                            \/\/ a should not be same as either i or j<br\/>                            if (graph[i][a] != INF &amp;&amp; i != a &amp;&amp;<br\/>                                    j!= a &amp;&amp; sp[a][j][e-1] != INF)<br\/>                                sp[i][j][e] = Math.min(sp[i][j][e],<br\/>                                          graph[i][a] + sp[a][j][e-1]);<br\/>                        }<br\/>                    }<br\/>                }<br\/>            }<br\/>        }<br\/>        return sp[u][v][k];<br\/>    }<br\/> <br\/>    public static void main (String[] args)<br\/>    {<br\/>        \/* Let us create the graph shown in above diagram*\/<br\/>        int graph[][] = new int[][]{ {0, 10, 3, 2},<br\/>                                     {INF, 0, INF, 7},<br\/>                                     {INF, INF, 0, 6},<br\/>                                     {INF, INF, INF, 0}<br\/>                                   };<br\/>        ShortestPath t = new ShortestPath();<br\/>        int u = 0, v = 3, k = 2;<br\/>        System.out.println(&quot;Weight of the shortest path is &quot;+<br\/>                           t.shortestPath(graph, u, v, k));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Weight of the shortest path is 9\r\n\r\n<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming Shortest path with exactly k edges in a directed and weighted graph The graph is given as adjacency matrix representation where value<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,70146,2139],"tags":[76591,76589,71365,83690,76588,83689,79909,79912,79910,83691,79913,79907,76592],"class_list":["post-26783","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-analysis-of-algorithm","category-java","tag-dijkstra-algorithm-in-java-with-output","tag-dijkstra-algorithm-java-adjacency-matrix","tag-dijkstra-algorithm-java-code-download","tag-dijkstras-algorithm-in-java-using-adjacency-list","tag-dijkstras-algorithm-java-using-priority-queue","tag-implementation-of-dijkstras-shortest-path-algorithm-in-java","tag-k-shortest-path-algorithm","tag-shortest-path-between-two-nodes-in-a-graph","tag-shortest-path-in-graph","tag-shortest-path-unweighted-graph-java","tag-shortest-path-with-at-most-k-edges","tag-shortest-path-with-minimum-number-of-edges","tag-single-source-shortest-path-program-in-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26783","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=26783"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26783\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26783"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26783"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26783"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}