<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lester Ford Jr. &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/lester-ford-jr/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Bellman-Ford Shortest Path in a Graph</title>
		<link>/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/</link>
		<comments>/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/#comments</comments>
		<pubDate>Mon, 22 Oct 2012 13:55:28 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Algebraic graph theory]]></category>
		<category><![CDATA[Bellman–Ford algorithm]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Floyd–Warshall algorithm]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Lester Ford Jr.]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Matrix]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Richard E. Bellman]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[The algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>

		<guid isPermaLink="false">/?p=3417</guid>
		<description><![CDATA[Introduction As we saw in the previous post, the algorithm of Dijkstra is very useful when it comes to find all the shortest paths in a weighted graph. However it has one major problem! Obviously it doesn’t work correctly when dealing with negative lengths of the edges. We know that the algorithm works perfectly when &#8230; <a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Bellman-Ford Shortest Path in a Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>As we saw in the previous post, <a title="Computer Algorithms: Dijkstra Shortest Path in a Graph" href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/">the algorithm of Dijkstra</a> is very useful when it comes to find all the shortest paths in a weighted graph. However it has one major problem! Obviously it doesn’t work correctly when dealing with negative lengths of the edges.</p>
<p>We know that the algorithm works perfectly when it comes to positive edges, and that is absolutely normal because we try to optimize the inequality of the triangle.</p>
<figure id="attachment_3420" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-Dijkstras-Approach.png"><img class="size-full wp-image-3420" title="Dijkstra's Approach" src="/wp-content/uploads/2012/10/1.-Dijkstras-Approach.png" alt="Dijkstra's Approach" width="620" height="399" srcset="/wp-content/uploads/2012/10/1.-Dijkstras-Approach.png 620w, /wp-content/uploads/2012/10/1.-Dijkstras-Approach-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Since all the edges are positive we get the closest one!</figcaption></figure>
<p>Since Dijkstra’s algorithm make use of a priority queue normally we get first the shortest adjacent edge to the starting point. In our very basic example we’ll get first the edge with the length of 3 -&gt; (S, A).</p>
<p>However when it comes to negative edges we can&#8217;t use any more priority queues, so we need a different, yet working solution.<span id="more-3417"></span></p>
<h2>Overview</h2>
<p>The solution was published by <a title="Richard E. Bellman" href="http://en.wikipedia.org/wiki/Richard_Bellman" target="_blank">Richard E. Bellman</a> and <a title="Lester Ford, Jr." href="http://en.wikipedia.org/wiki/L._R._Ford,_Jr." target="_blank">Lester Ford, Jr.</a> in 1958 in their publication &#8220;On a Routing Problem&#8221; and it is quite simple to explain and understand. Since we can prioritize the edges by its lengths the only thing we should do is to calculate <span style="text-decoration: underline;">all</span> the paths. And to be sure that our algorithm will find all the paths correctly we repeat that N-1 times, where N is the number of vertices (|V| = N)!</p>
<figure id="attachment_3421" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-Bellman-Ford-Approach.png"><img src="/wp-content/uploads/2012/10/2.-Bellman-Ford-Approach.png" alt="Bellman-Ford Approach" title="Bellman-Ford Approach" width="620" height="399" class="size-full wp-image-3421" srcset="/wp-content/uploads/2012/10/2.-Bellman-Ford-Approach.png 620w, /wp-content/uploads/2012/10/2.-Bellman-Ford-Approach-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The algorithm of Bellman-Ford doesn&#8217;t use priority queues! Indeed they are useless since the closest node in the queue can have shorter path passing through another node!</figcaption></figure>
<p>In this very basic image we can see how Bellman-Ford solves the problem. First we get the distances from S to A and B, which are respectively 3 and 4, but there is a shorter path to A, which passes through B and it is (S, B) + (B, A) = 4 – 2 = 2.</p>
<h2>Code</h2>
<p>Here’s the code on <a href="/category/php/" title="PHP on Stoimen.com">PHP</a>. Note that this time we use an adjacency matrix and an additional array of distances. It’s important (for directed graphs, and our graph this time is directed) to put the positive value of A[j][i] if A[i][j] is negative. Note the case for A[1][2]!</p>
<pre lang="PHP">
define('INFINITY', 10000000);

$matrix = array(
    0 => array( 0,  3,  4),
    1 => array( 0,  0,  2),
    2 => array( 0,  -2, 0),
);

$len = count($matrix);

$dist = array();

function BellmanFord(&$matrix, &$dist, $start)
{
    global $len;
    
    foreach (array_keys($matrix) as $vertex) {
        $dist[$vertex] = INFINITY;
        if ($vertex == $start) {
            $dist[$vertex] = 0;
        }
    }
    
    for ($k = 0; $k < $len - 1; $k++) {
        for ($i = 0; $i < $len; $i++) {
            for ($j = 0; $j < $len; $j++) {
                if ($dist[$i] > $dist[$j] + $matrix[$j][$i]) {
                    $dist[$i] = $dist[$j] + $matrix[$j][$i];
                }
            }
        }
    }
}

BellmanFord($matrix, $dist, 0);

// [0, 2, 4]
print_r($dist);
</pre>
<h3>Complexity</h3>
<p>The complexity is clearly O(n<sup>3</sup>) which follows directly from the code above.</p>
<h2>Application</h2>
<p>Actually this algorithm is very useful and it not only works with negative weights, but also can help us find negative cycles in the graph.</p>
<figure id="attachment_3422" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-Negative-Cycles.png"><img src="/wp-content/uploads/2012/10/3.-Negative-Cycles.png" alt="Negative Cycles" title="Negative Cycles" width="620" height="399" class="size-full wp-image-3422" srcset="/wp-content/uploads/2012/10/3.-Negative-Cycles.png 620w, /wp-content/uploads/2012/10/3.-Negative-Cycles-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A negative cycle can be found with Bellman-Ford&#8217;s algorithm!</figcaption></figure>
<p>This is done with the simple check after the main loop.</p>
<pre lang="PHP">
    for ($i = 0; $i < $len; $i++) {
        for ($j = 0; $j < $len; $j++) {
            if ($dist[$i] > $dist[$j] + $matrix[$j][$i]) {
                echo 'The graph contains a negative cycle!';
            }
        }
    }
</pre>
<p>And here&#8217;s the full code.</p>
<pre lang="PHP">
$matrix = array(
    0 => array( 0,  3,  4),
    1 => array( 0,  0,  2),
    2 => array( 0,  -2, 0),
);

$len = count($matrix);

$dist = array();

function BellmanFord(&$matrix, &$dist, $start)
{
    global $len;
    
    foreach (array_keys($matrix) as $vertex) {
        $dist[$vertex] = INFINITY;
        if ($vertex == $start) {
            $dist[$vertex] = 0;
        }
    }
    
    for ($k = 0; $k < $len - 1; $k++) {
        for ($i = 0; $i < $len; $i++) {
            for ($j = 0; $j < $len; $j++) {
                if ($dist[$i] > $dist[$j] + $matrix[$j][$i]) {
                    $dist[$i] = $dist[$j] + $matrix[$j][$i];
                }
            }
        }
    }
    
    for ($i = 0; $i < $len; $i++) {
        for ($j = 0; $j < $len; $j++) {
            if ($dist[$i] > $dist[$j] + $matrix[$j][$i]) {
                echo 'The graph contains a negative cycle!';
            }
        }
    }
}

BellmanFord($matrix, $dist, 0);

// [0, 2, 4]
print_r($dist);
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
