{"id":26833,"date":"2018-01-02T21:10:06","date_gmt":"2018-01-02T15:40:06","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26833"},"modified":"2018-01-02T21:10:06","modified_gmt":"2018-01-02T15:40:06","slug":"c-programming-bellman-ford-algorithm","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-bellman-ford-algorithm\/","title":{"rendered":"Cpp Programming &#8211; Bellman\u2013Ford Algorithm"},"content":{"rendered":"<p>Given a graph and a source vertex <em>src <\/em>in graph, find shortest paths from <em>src <\/em>to all vertices in the given graph. The graph may contain negative weight edges.<span id=\"more-27914\"><\/span><br \/>\nWe have discussed Dijkstra\u2019s algorithm for this problem. Dijksra\u2019s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). <em>Dijkstra doesn\u2019t work for Graphs with negative weight edges, Bellman-Ford works for such graphs. Bellman-Ford is also simpler than Dijkstra and suites well for distributed systems. But time complexity of Bellman-Ford is O(VE), which is more than Dijkstra.<\/em><\/p>\n<p><strong>Algorithm<\/strong><br \/>\nFollowing are the detailed steps.<\/p>\n<p><em>Input:<\/em> Graph and a source vertex <em>src<\/em><br \/>\n<em>Output:<\/em> Shortest distance to all vertices from <em>src<\/em>. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.<\/p>\n<ul>\n<li>This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.<\/li>\n<li>This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph.\n<ul>\n<li>\u2026..Do following for each edge u-v<br \/>\n\u2026\u2026\u2026\u2026\u2026\u2026If dist[v] &gt; dist[u] + weight of edge uv, then update dist[v]\n\u2026\u2026\u2026\u2026\u2026\u2026\u2026.dist[v] = dist[u] + weight of edge uv<\/li>\n<\/ul>\n<\/li>\n<li>This step reports if there is a negative weight cycle in graph. Do following for each edge u-v<br \/>\n\u2026\u2026If dist[v] &gt; dist[u] + weight of edge uv, then \u201cGraph contains negative weight cycle\u201d<br \/>\nThe idea of step 3 is, step 2 guarantees shortest distances if graph doesn\u2019t contain negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle<\/li>\n<\/ul>\n<p><em><strong>How does this work?<\/strong><\/em> Like other Dynamic Programming Problems, the algorithm calculate shortest paths in bottom-up manner. It first calculates the shortest distances for the shortest paths which have at-most one edge in the path. Then, it calculates shortest paths with at-nost 2 edges, and so on. After the ith iteration of outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| \u2013 1 edges in any simple path, that is why the outer loop runs |v| \u2013 1 times. The idea is, assuming that there is no negative weight cycle, if we have calculated shortest paths with at most i edges, then an iteration over all edges guarantees to give shortest path with at-most (i+1) edges.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Example<\/strong><br \/>\nLet us understand the algorithm with following example graph. The images are taken from this source.<\/p>\n<p>Let the given source vertex be 0. Initialize all distances as infinite, except the distance to source itself. Total number of vertices in the graph is 5, so <em>all edges must be processed 4 times.<\/em><\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"size-full wp-image-27000 aligncenter\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-Algorithm.png\" alt=\"Bellman Algorithm\" width=\"439\" height=\"187\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-Algorithm.png 439w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-Algorithm-300x128.png 300w\" sizes=\"(max-width: 439px) 100vw, 439px\" \/><\/p>\n<p>Let all edges are processed in following order: (B,E), (D,B), (B,D), (A,B), (A,C), (D,C), (B,C), (E,D). We get following distances when all edges are processed first time. The first row in shows initial distances. The second row shows distances when edges (B,E), (D,B), (B,D) and (A,B) are processed. The third row shows distances when (A,C) is processed. The fourth row shows when (D,C), (B,C) and (E,D) are processed.<\/p>\n<p><img decoding=\"async\" class=\"size-full wp-image-27006 aligncenter\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford.png\" alt=\"Bellman ford\" width=\"441\" height=\"205\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford.png 441w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford-300x139.png 300w\" sizes=\"(max-width: 441px) 100vw, 441px\" \/><\/p>\n<p>The first iteration guarantees to give all shortest paths which are at most 1 edge long. We get following distances when all edges are processed second time (The last row shows final values).<\/p>\n<p><img decoding=\"async\" class=\"size-full wp-image-27009 aligncenter\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford-algorithm.png\" alt=\"Bellman ford algorithm\" width=\"430\" height=\"227\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford-algorithm.png 430w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Bellman-ford-algorithm-300x158.png 300w\" sizes=\"(max-width: 430px) 100vw, 430px\" \/><\/p>\n<p>The second iteration guarantees to give all shortest paths which are at most 2 edges long. The algorithm processes all edges 2 more times. The distances are minimized after the second iteration, so third and fourth iterations don\u2019t update the distances.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C \/ C++ program for Bellman-Ford&#039;s single source <br\/>\/\/ shortest path algorithm.<br\/> <br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/>#include &lt;string.h&gt;<br\/>#include &lt;limits.h&gt;<br\/> <br\/>\/\/ a structure to represent a weighted edge in graph<br\/>struct Edge<br\/>{<br\/>    int src, dest, weight;<br\/>};<br\/> <br\/>\/\/ a structure to represent a connected, directed and <br\/>\/\/ weighted graph<br\/>struct Graph<br\/>{<br\/>    \/\/ V-&gt; Number of vertices, E-&gt; Number of edges<br\/>    int V, E;<br\/> <br\/>    \/\/ graph is represented as an array of edges.<br\/>    struct Edge* edge;<br\/>};<br\/> <br\/>\/\/ Creates a graph with V vertices and E edges<br\/>struct Graph* createGraph(int V, int E)<br\/>{<br\/>    struct Graph* graph = <br\/>         (struct Graph*) malloc( sizeof(struct Graph) );<br\/>    graph-&gt;V = V;<br\/>    graph-&gt;E = E;<br\/> <br\/>    graph-&gt;edge = <br\/>       (struct Edge*) malloc( graph-&gt;E * sizeof( struct Edge ) );<br\/> <br\/>    return graph;<br\/>}<br\/> <br\/>\/\/ A utility function used to print the solution<br\/>void printArr(int dist[], int n)<br\/>{<br\/>    printf(&quot;Vertex   Distance from Source\\n&quot;);<br\/>    for (int i = 0; i &lt; n; ++i)<br\/>        printf(&quot;%d \\t\\t %d\\n&quot;, i, dist[i]);<br\/>}<br\/> <br\/>\/\/ The main function that finds shortest distances from src to<br\/>\/\/ all other vertices using Bellman-Ford algorithm.  The function<br\/>\/\/ also detects negative weight cycle<br\/>void BellmanFord(struct Graph* graph, int src)<br\/>{<br\/>    int V = graph-&gt;V;<br\/>    int E = graph-&gt;E;<br\/>    int dist[V];<br\/> <br\/>    \/\/ Step 1: Initialize distances from src to all other vertices<br\/>    \/\/ as INFINITE<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        dist[i]   = INT_MAX;<br\/>    dist[src] = 0;<br\/> <br\/>    \/\/ Step 2: Relax all edges |V| - 1 times. A simple shortest <br\/>    \/\/ path from src to any other vertex can have at-most |V| - 1 <br\/>    \/\/ edges<br\/>    for (int i = 1; i &lt;= V-1; i++)<br\/>    {<br\/>        for (int j = 0; j &lt; E; j++)<br\/>        {<br\/>            int u = graph-&gt;edge[j].src;<br\/>            int v = graph-&gt;edge[j].dest;<br\/>            int weight = graph-&gt;edge[j].weight;<br\/>            if (dist[u] != INT_MAX &amp;&amp; dist[u] + weight &lt; dist[v])<br\/>                dist[v] = dist[u] + weight;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Step 3: check for negative-weight cycles.  The above step <br\/>    \/\/ guarantees shortest distances if graph doesn&#039;t contain <br\/>    \/\/ negative weight cycle.  If we get a shorter path, then there<br\/>    \/\/ is a cycle.<br\/>    for (int i = 0; i &lt; E; i++)<br\/>    {<br\/>        int u = graph-&gt;edge[i].src;<br\/>        int v = graph-&gt;edge[i].dest;<br\/>        int weight = graph-&gt;edge[i].weight;<br\/>        if (dist[u] != INT_MAX &amp;&amp; dist[u] + weight &lt; dist[v])<br\/>            printf(&quot;Graph contains negative weight cycle&quot;);<br\/>    }<br\/> <br\/>    printArr(dist, V);<br\/> <br\/>    return;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/* Let us create the graph given in above example *\/<br\/>    int V = 5;  \/\/ Number of vertices in graph<br\/>    int E = 8;  \/\/ Number of edges in graph<br\/>    struct Graph* graph = createGraph(V, E);<br\/> <br\/>    \/\/ add edge 0-1 (or A-B in above figure)<br\/>    graph-&gt;edge[0].src = 0;<br\/>    graph-&gt;edge[0].dest = 1;<br\/>    graph-&gt;edge[0].weight = -1;<br\/> <br\/>    \/\/ add edge 0-2 (or A-C in above figure)<br\/>    graph-&gt;edge[1].src = 0;<br\/>    graph-&gt;edge[1].dest = 2;<br\/>    graph-&gt;edge[1].weight = 4;<br\/> <br\/>    \/\/ add edge 1-2 (or B-C in above figure)<br\/>    graph-&gt;edge[2].src = 1;<br\/>    graph-&gt;edge[2].dest = 2;<br\/>    graph-&gt;edge[2].weight = 3;<br\/> <br\/>    \/\/ add edge 1-3 (or B-D in above figure)<br\/>    graph-&gt;edge[3].src = 1;<br\/>    graph-&gt;edge[3].dest = 3;<br\/>    graph-&gt;edge[3].weight = 2;<br\/> <br\/>    \/\/ add edge 1-4 (or A-E in above figure)<br\/>    graph-&gt;edge[4].src = 1;<br\/>    graph-&gt;edge[4].dest = 4;<br\/>    graph-&gt;edge[4].weight = 2;<br\/> <br\/>    \/\/ add edge 3-2 (or D-C in above figure)<br\/>    graph-&gt;edge[5].src = 3;<br\/>    graph-&gt;edge[5].dest = 2;<br\/>    graph-&gt;edge[5].weight = 5;<br\/> <br\/>    \/\/ add edge 3-1 (or D-B in above figure)<br\/>    graph-&gt;edge[6].src = 3;<br\/>    graph-&gt;edge[6].dest = 1;<br\/>    graph-&gt;edge[6].weight = 1;<br\/> <br\/>    \/\/ add edge 4-3 (or E-D in above figure)<br\/>    graph-&gt;edge[7].src = 4;<br\/>    graph-&gt;edge[7].dest = 3;<br\/>    graph-&gt;edge[7].weight = -3;<br\/> <br\/>    BellmanFord(graph, 0);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Vertex   Distance from Source\r\n0                0\r\n1                -1\r\n2                2\r\n3                -2\r\n4                1<\/pre>\n<p><strong>Notes<\/strong><\/p>\n<ul>\n<li>Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.<\/li>\n<li>Bellman-Ford works better (better than Dijksra\u2019s) for distributed systems. Unlike Dijksra\u2019s where we need to find minimum value of all vertices, in Bellman-Ford, edges are considered one by one.<\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming &#8211; Bellman Ford Algorithm &#8211; Dynamic Programming Given a graph and a source vertex src in graph, find shortest paths from src to all vertices<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[83515,1,70145],"tags":[80697,80694,74001,78437,78465,78379,80696,80700,78380,70483,72841,72848,72840,80687],"class_list":["post-26833","post","type-post","status-publish","format-standard","hentry","category-c-programming-3","category-coding","category-dynamic-programming","tag-bellman-algorithm","tag-bellman-ford","tag-bellman-ford-algorithm","tag-bellman-ford-algorithm-c","tag-bellman-ford-algorithm-c-code","tag-bellman-ford-algorithm-example","tag-bellman-ford-example","tag-bellman-ford-java","tag-bellman-ford-pseudocode","tag-dynamic-programming","tag-dynamic-programming-c","tag-dynamic-programming-code-generation-algorithm","tag-dynamic-programming-definition","tag-dynamic-programming-for-shortest-path-problem"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26833","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=26833"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26833\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26833"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26833"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}