<?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>Graph &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/graph/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: Topological Sort Revisited</title>
		<link>/2012/12/10/computer-algorithms-topological-sort-revisited/</link>
		<comments>/2012/12/10/computer-algorithms-topological-sort-revisited/#comments</comments>
		<pubDate>Mon, 10 Dec 2012 15:45:16 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Adjacency list]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph algorithms]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[time consuming algorithm]]></category>
		<category><![CDATA[Topological sorting]]></category>
		<category><![CDATA[Vertex]]></category>

		<guid isPermaLink="false">/?p=3494</guid>
		<description><![CDATA[Introduction We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm. We have a directed acyclic graph (DAG). There are no &#8230; <a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Topological Sort Revisited</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<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/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>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm.</p>
<p>We have a directed acyclic graph (DAG). There are no cycles so we must go for some kind of order putting all the vertices of the graph in such an order, that if there’s a directed edge (u, v), u must precede v in that order. </p>
<figure id="attachment_3506" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/1.-Topological-Sort.png"><img src="/wp-content/uploads/2012/12/1.-Topological-Sort.png" alt="Topological Sort" title="Topological Sort" width="620" height="399" class="size-full wp-image-3506" srcset="/wp-content/uploads/2012/12/1.-Topological-Sort.png 620w, /wp-content/uploads/2012/12/1.-Topological-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>The process of putting all the vertices of the DAG in such an order is called topological sorting. It’s commonly used in task scheduling or while finding the shortest paths in a DAG.</p>
<p>The algorithm itself is pretty simple to understand and code. We must start from the vertex (vertices) that don’t have predecessors. </p>
<p><figure id="attachment_3513" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png"><img src="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png" alt="Topological Sort - step 1" title="Topological Sort - step 1" width="620" height="399" class="size-full wp-image-3513" srcset="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png 620w, /wp-content/uploads/2012/12/2.-Topological-Sort-step-1-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure><span id="more-3494"></span></p>
<p>We put them in our sorted list in random order. Since they don’t depend on each other we can assume they are equally sorted already. Indeed thinking of a task schedule if there are tasks that don’t have predecessors (they don’t depend on other tasks before them) and that don’t depend on each other we can put them in random order (and execute them in random order).</p>
<figure id="attachment_3512" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png"><img src="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png" alt="Topological Sort - Order" title="Topological Sort - Order" width="620" height="399" class="size-full wp-image-3512" srcset="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png 620w, /wp-content/uploads/2012/12/3.-Topological-Sort-Order-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Once we have the vertices with no predecessors we must remove the edges starting from them. Then – go again with the vertices with no predecessors. </p>
<figure id="attachment_3511" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png"><img src="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png" alt="Topological Sort - step 2" title="Topological Sort - step 2" width="620" height="399" class="size-full wp-image-3511" srcset="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png 620w, /wp-content/uploads/2012/12/4.-Topological-Sort-step-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>It’s as simple as that, so why do we need a revision of this algorithm? Well, basically because of its efficiency. </p>
<h2>Overview</h2>
<p>As we know most of the graph algorithms depend on the way the graph is represented in our application. We consider as the two main representations the adjacency matrix … </p>
<figure id="attachment_3510" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png"><img src="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png" alt="Adjacency Matrix" title="Adjacency Matrix" width="620" height="399" class="size-full wp-image-3510" srcset="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/12/5.-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>… and adjacency lists.</p>
<figure id="attachment_3509" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png" alt="Adjacency Lists" title="Adjacency Lists" width="620" height="399" class="size-full wp-image-3509" srcset="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/6.-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Let’s first take a look of some of the main approaches to get the topologically sorted list at the end of the algorithm. </p>
<p>What can we do in order to find the vertices with no predecessors? We can only scan the entire list of vertices. </p>
<h3>Adjacency Matrix</h3>
<p>In case we’re using adjacency matrix we need|V|^2 space to store the graph. To find the vertices with no predecessors we have to scan the entire graph, which will cost us O(|V|^2) time.  And we’ll have to do that |V| times. This will be |V|^3 time consuming algorithm and for dense graphs this will be quite an ineffective algorithm.</p>
<h3>Adjacency Lists</h3>
<p>What about the adjacency list? There we need |E| space to store a directed graph. How fast can we find a node with no predecessor? Practically we’ll need O(|E|) time.  Thus in the worst case we have again O(|V|^2) time consuming programs.</p>
<p>So what can be done in order to optimize this algorithm?</p>
<p>Practically we can start by picking up a random vertex and “go back” until we get a node with no predecessors. This approach can be very effective yet also very ineffective. First of all if we have to scan all the way back to a node with no predecessors this will cost us |V| time, but if we stuck on a node that don’t have a preceding node then we’ll have a constant speed.</p>
<p>This means that we can modify the algorithm a bit in order to improve a lot the algorithm. We just need to store both incoming and outgoing edges and slightly modify the adjacency lists.</p>
<figure id="attachment_3508" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png" alt="Modified Adjacency Lists" title="Modified Adjacency Lists" width="620" height="399" class="size-full wp-image-3508" srcset="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>What’s the algorithm now?</p>
<p>First we easily find the nodes with no predecessors. Then, using a queue, we can keep the nodes with no predecessors and on each dequeue we can remove the edges from the node to all other nodes.</p>
<h2>Pseudo Code</h2>
<pre>
1. Represent the graph with two lists on each vertex (incoming edges and outgoing edges)
2. Make an empty queue Q;
3. Make an empty topologically sorted list T;
4. Push all items with no predecessors in Q;
5. While Q is not empty
   a. Dequeue from Q into u;
   b. Push u in T;
   c. Remove all outgoing edges from u;
6. Return T;
</pre>
<p>This approach will give us a better performance than the “brute force” approach. The running time complexity is O(|V| + |E|). The problem is that we need additional space and an operational queue, but this approach is a perfect example of how by using additional space you can get a better performing algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<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/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>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/12/10/computer-algorithms-topological-sort-revisited/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Dijkstra Shortest Path in a Graph</title>
		<link>/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/</link>
		<comments>/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/#comments</comments>
		<pubDate>Mon, 15 Oct 2012 14:12:50 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[BFS algorithm]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Dijkstra algorithm]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Distance]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[library SPL]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[The algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3381</guid>
		<description><![CDATA[Introduction We already know how we can find the shortest paths in a graph starting from a given vertex. Practically we modified breadth-first search in order to calculate the distances from s to all other nodes reachable from s. We know that this works because BFS walks through the graph level by level. Some sources &#8230; <a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Dijkstra 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/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/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/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford 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>We already know how we can find the shortest paths in a graph starting from a given vertex. Practically we modified breadth-first search in order to calculate the distances from s to all other nodes reachable from s. We know that this works because BFS walks through the graph level by level.</p>
<figure id="attachment_3397" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png"><img src="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png" alt="BFS Shortest Paths" title="BFS Shortest Paths" width="620" height="399" class="size-full wp-image-3397" srcset="/wp-content/uploads/2012/10/1.-BFS-Shortest-Paths.png 620w, /wp-content/uploads/2012/10/1.-BFS-Shortest-Paths-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">BFS is often used to find shortest paths between a starting node (s) and all other reachable nodes in a graph!</figcaption></figure>
<p>Some sources give a very simple explanation of how BFS finds the shortest paths in a graph. We must just think of the graph as a set of balls connected through strings. </p>
<figure id="attachment_3398" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png"><img src="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png" alt="The Graph as Balls and Strings" title="The Graph as Balls and Strings" width="620" height="399" class="size-full wp-image-3398" srcset="/wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings.png 620w, /wp-content/uploads/2012/10/2.-The-Graph-as-Balls-and-Strings-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can think of a graph as a set of balls connected through strings!</figcaption></figure>
<p>As we can see by lifting the ball called “S” all other balls fall down. The closest balls are directly connected to “s” and this is the first level, while the outermost balls are those with longest paths.</p>
<figure id="attachment_3399" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png"><img src="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png" alt="The Graph as Balls and Strings Levels" title="The Graph as Balls and Strings Levels" width="620" height="399" class="size-full wp-image-3399" srcset="/wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels.png 620w, /wp-content/uploads/2012/10/3.-The-Graph-as-Balls-and-Strings-Levels-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Breadth-first search works much like the image above &#8211; it explores the graph level by level, thus we&#8217;re sure that all the paths are the shortest!</figcaption></figure>
<p>Clearly edges like those between A and B doesn’t matter for our BFS algorithm because they don’t make the path from S to C through B shorter. This is also known as the triangle inequality, where the sum of the lengths of two of the sides of the triangle is always greater than the length of the third side.</p>
<figure id="attachment_3400" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/4.-Triangle-inequality.png"><img src="/wp-content/uploads/2012/10/4.-Triangle-inequality.png" alt="Triangle inequality" title="Triangle inequality" width="620" height="399" class="size-full wp-image-3400" srcset="/wp-content/uploads/2012/10/4.-Triangle-inequality.png 620w, /wp-content/uploads/2012/10/4.-Triangle-inequality-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">What the triangle inequality says us is that if we have a direct edge between two nodes &#8211; that must be the shortest path between them!</figcaption></figure>
<p>We must only answer the question is BFS the best algorithm that finds the shortest path between any two nodes of the graph? This is a reasonable question because as we know by using BFS we don’t find only the shortest path between given vertices i and j, but we also get the shortest paths between i and all other vertices of G. This is an information that we actually don’t need, but can we find the shortest path between i and j without that info?<span id="more-3381"></span></p>
<p>The answer is simply “no”! Practically depth-first search can’t help us. Even worse &#8211; we can find paths that are far not the shortest ones.</p>
<figure id="attachment_3401" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png"><img src="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png" alt="DFS and shortest path" title="DFS and shortest path" width="620" height="399" class="size-full wp-image-3401" srcset="/wp-content/uploads/2012/10/5.-DFS-and-shortest-path.png 620w, /wp-content/uploads/2012/10/5.-DFS-and-shortest-path-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">DFS actually can find the longest path in some cases and can&#8217;t be used for finding shortest path!</figcaption></figure>
<p>In the image above using DFS the distance between 1 and 7 is 7 while practically there is an edge between them.</p>
<p>So BFS is the optimal algorithm for finding shortest paths in a graph. But there’s a catch! This algorithm works fine when we assume that all the edges are the same length. In the examples so far each edge has the value of 1. So N edges between s and i made the distance between them of a length N.</p>
<h2>Overview</h2>
<p>As we know in practice different edges can have different values. Exactly that was the case in weighted graphs. Going back to the road map example the distances between different cities are commonly evaluated in miles or kilometers. Of course we can associate any other meaningful value to this edges. This can be either time in hours to travel between cities, money for fuel or anything else.</p>
<figure id="attachment_3403" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png"><img src="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png" alt="Weighted Graphs in Practice" title="Weighted Graphs in Practice" width="620" height="399" class="size-full wp-image-3403" srcset="/wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice.png 620w, /wp-content/uploads/2012/10/6.-Weighted-Graphs-in-Practice-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In practice is more common to use weighted graphs than non-weighted graphs!</figcaption></figure>
<p>Now BFS can’t help us any more. Why? Because using non-equal values for the edges the triangle inequality is no longer true. Now the edge (the direct path) between A and B can be greater than the sum of the two edges (A, C) + (C, B)!</p>
<figure id="attachment_3404" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png"><img src="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png" alt="Triangle Inequality Problem" title="Triangle Inequality Problem" width="620" height="399" class="size-full wp-image-3404" srcset="/wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem.png 620w, /wp-content/uploads/2012/10/7.-Triangle-Inequality-Problem-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In a weighted graph the edges aren&#8217;t equal for our BFS algorithm so we can&#8217;t use it!</figcaption></figure>
<p>In other words, assuming the same abstraction with balls and wires the hanging wires can’t be discarded so easily.</p>
<figure id="attachment_3405" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png"><img src="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png" alt="Weighted Graph as Balls and Strings" title="Weighted Graph as Balls and Strings" width="620" height="399" class="size-full wp-image-3405" srcset="/wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings.png 620w, /wp-content/uploads/2012/10/8.-The-Graph-as-Balls-and-Strings-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">On weighted graphs BFS is no longer useful!</figcaption></figure>
<p>So now how can we solve this problem? A very dummy approach is to break apart each edge with dummy vertices in order to make BFS work again.</p>
<figure id="attachment_3406" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png"><img src="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png" alt="Breaking apart edges" title="Breaking apart edges" width="620" height="399" class="size-full wp-image-3406" srcset="/wp-content/uploads/2012/10/9.-Breaking-apart-edges.png 620w, /wp-content/uploads/2012/10/9.-Breaking-apart-edges-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Since the graph is weighted we can decompose its edges to more &#8220;dummy&#8221; edges!</figcaption></figure>
<p>However this approach has several weak points. The major one is that we’ll have to keep much more information, which means more memory usage, for even small graphs. This is done in case we break each edge on too many parts.</p>
<p>The solution of this problem was given by <a href="http://en.wikipedia.org/wiki/Edsger_W._Dijkstra" title="Edsger W. Dijkstra" target="_blank">Edsger Dijkstra</a> in 1956 and published in 1959. The only thing we should do now is to be sure that even discarding the triangle inequality we have the shortest paths. The first thing to do is to keep information for the distance from s to the parent (previous) node of i in the graph in order to calculate which distance is shorter.</p>
<p>In BFS we used a queue in order to walk through all the ancestors of a node. This was made consecutively. Thus for the graph G on the next image the order of enqueuing the ancestors of S was A, B, C.</p>
<figure id="attachment_3409" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png"><img src="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png" alt="Order of enqueuing" title="Order of enqueuing" width="620" height="399" class="size-full wp-image-3409" srcset="/wp-content/uploads/2012/10/10.-Order-of-enqueuing.png 620w, /wp-content/uploads/2012/10/10.-Order-of-enqueuing-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The order of enqueuing in BFS is consecutive &#8211; something that isn&#8217;t working for weighted graphs!</figcaption></figure>
<p>The Dijkstra’s algorithm make use of a priority queue, also know as a heap. This fact combined by the fact we keep info for the shortest path so far help us find shortest paths in a weighted graphs.</p>
<p>Why this works? To answer this question let’s see the next very basic example, assuming the graph G from the next image. As we can see the triangle inequality isn’t true.</p>
<figure id="attachment_3410" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/11.-Weighted-graph.png"><img src="/wp-content/uploads/2012/10/11.-Weighted-graph.png" alt="Weighted graph" title="Weighted graph" width="620" height="399" class="size-full wp-image-3410" srcset="/wp-content/uploads/2012/10/11.-Weighted-graph.png 620w, /wp-content/uploads/2012/10/11.-Weighted-graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A weighted graph that doesn&#8217;t follow the triangle inequality!</figcaption></figure>
<p>OK, we see that the path [S, B, A] is shorter than [S, A] although the edge (S, A) exists. How the Dijkstra algorithm overcomes this problem.</p>
<p>First we have no information about the distances (S, A) and (S, B), the only thing we know is that S is the starting point, its distance is 0 and its path so far is the empty set. So first we enqueue in a priority the distances from S to A and B.</p>
<figure id="attachment_3411" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png"><img src="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png" alt="Dijkstra Priority Queue" title="Dijkstra Priority Queue" width="620" height="399" class="size-full wp-image-3411" srcset="/wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue.png 620w, /wp-content/uploads/2012/10/12.-Dijkstra-Priority-Queue-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The algorithm of Dijkstra make use of a priority queue!</figcaption></figure>
<p>Now we dequeue the minimum (first in the heap) element from the queue &#8211; the closest node to S, which is B. Then all the nodes adjacent to S in the queue are tested for adjacency to B, thus if we have already the distance between S and A now we can test if its longer than (S, B) + (B, A) &#8211; the triangle inequality!</p>
<p>So far we know that we must change a bit BFS to get the Dijkstra algorithm. The only thing to do is to keep info for each node for the path through its parent and to use a priority queue.</p>
<h2>Code</h2>
<p>Implementing this algorithms isn’t much more difficult than BFS, so here’s the code in <a href="/category/php/" title="PHP on Stoimen.com">PHP</a>. However this example make use of the standard php library SPL and the PriorityQueue data structure, but any developer can code <a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" title="Computer Algorithms: Heap and Heapsort">his own heap</a>.</p>
<p>Here&#8217;s the graph from the code:</p>
<figure id="attachment_3413" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/0.-Graph.png"><img src="/wp-content/uploads/2012/10/0.-Graph.png" alt="The Graph from the Code" title="The Graph from the Code" width="620" height="399" class="size-full wp-image-3413" srcset="/wp-content/uploads/2012/10/0.-Graph.png 620w, /wp-content/uploads/2012/10/0.-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The graph!</figcaption></figure>
<pre lang="PHP">
class vertex
{
    public $key         = null;
    public $visited     = 0;
    public $distance    = 1000000;  // infinite
    public $parent      = null;
    public $path        = null;
    
    public function __construct($key) 
    {
        $this->key  = $key;
    }
}

class PriorityQueue extends SplPriorityQueue
{
    public function compare($a, $b)
    {
        if ($a === $b) return 0;
        return $a > $b ? -1 : 1;
    }
}

$v0 = new vertex(0);
$v1 = new vertex(1);
$v2 = new vertex(2);
$v3 = new vertex(3);
$v4 = new vertex(4);
$v5 = new vertex(5);

$list0 = new SplDoublyLinkedList();
$list0->push(array('vertex' => $v1, 'distance' => 3));
$list0->push(array('vertex' => $v3, 'distance' => 1));
$list0->rewind();

$list1 = new SplDoublyLinkedList();
$list1->push(array('vertex' => $v0, 'distance' => 3));
$list1->push(array('vertex' => $v2, 'distance' => 7));
$list1->rewind();

$list2 = new SplDoublyLinkedList();
$list2->push(array('vertex' => $v1, 'distance' => 7));
$list2->push(array('vertex' => $v3, 'distance' => 8));
$list2->push(array('vertex' => $v4, 'distance' => 12));
$list2->rewind();

$list3 = new SplDoublyLinkedList();
$list3->push(array('vertex' => $v0, 'distance' => 1));
$list3->push(array('vertex' => $v2, 'distance' => 8));
$list3->rewind();

$list4 = new SplDoublyLinkedList();
$list4->push(array('vertex' => $v2, 'distance' => 12));
$list4->push(array('vertex' => $v5, 'distance' => 3));
$list4->rewind();

$list5 = new SplDoublyLinkedList();
$list5->push(array('vertex' => $v4, 'distance' => 3));
$list5->rewind();

$adjacencyList = array(
    $list0,
    $list1,
    $list2,
    $list3,
    $list4,
    $list5,
);

function calcShortestPaths(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = new PriorityQueue();
    
    // push the starting vertex into the queue
    $q->insert($start, 0);
    $q->rewind();
    
    // mark the distance to it 0
    $start->distance = 0;
    
    // the path to the starting vertex
    $start->path = array($start->key);
    
    while ($q->valid()) {
        $t = $q->extract();
        $t->visited = 1;
        
        $l = $adjLists[$t->key];
        while ($l->valid()) {
            $item = $l->current();
            
            if (!$item['vertex']->visited) {
                if ($item['vertex']->distance > $t->distance + $item['distance']) {
                    $item['vertex']->distance = $t->distance + $item['distance'];
                    $item['vertex']->parent = $t;
                }
                
                $item['vertex']->path = array_merge($t->path, array($item['vertex']->key));
                
                $q->insert($item["vertex"], $item["vertex"]->distance);
            }
            $l->next();
        }
        $q->recoverFromCorruption();
        $q->rewind();
    }
}

calcShortestPaths($v0, $adjacencyList);

// The path from node 0 to node 5
// [0, 1, 2, 4, 5]
echo '[' . implode(', ', $v5->path) . ']';
</pre>
<h2>Complexity</h2>
<p>The complexity of that code is based on the complexity of BFS with the main difference that we keep a priority queue. For BFS we knew that the complexity was O(|V| + |E|), while Dijkstra&#8217;s algorithm has running time of O((|V| + |E|).log(|V|)). That is quite natural since the heapsort&#8217;s complexity is O(n.log(n))!</p>
<h2>Application</h2>
<p>Since the basic BFS can&#8217;t help us for weighted graphs and there are plenty of problems designed with weighted graphs obviously Dijkstra&#8217;s algorithm can be very handy. The only thing we should be aware of is the positive values of the edges.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/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/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford 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/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Topological Sort of a Graph</title>
		<link>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/</link>
		<comments>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/#comments</comments>
		<pubDate>Mon, 01 Oct 2012 12:03:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[basic graph algorithms]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph coloring]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[L]]></category>
		<category><![CDATA[Longest path problem]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[NP-complete problems]]></category>
		<category><![CDATA[Path decomposition]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[rational solution]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Topological sorting]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3367</guid>
		<description><![CDATA[Introduction Let’s assume we have a list of tasks to accomplish. Some of the tasks depend on others, so we must be very careful with the order of their execution. If the relationship between these tasks were simple enough we could represent them as a linked list, which would be great, and we would know &#8230; <a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Topological Sort of a Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
<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/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>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Let’s assume we have a list of tasks to accomplish. Some of the tasks depend on others, so we must be very careful with the order of their execution. If the relationship between these tasks were simple enough we could represent them as a linked list, which would be great, and we would know the exact order of their execution. The problem is that sometimes the relations between the different tasks are more complex and some tasks depend on two or more other tasks, which in their turn depend on one or more tasks, etc.</p>
<p>Thus we can’t model this problem using linked lists or trees. The only rational solution is to model the problem using a graph. What kind of graph do we need? Well, we definitely need a directed graph, to desribe the relations, and this graph shouldn&#8217;t have cycles. So we need the so called directed acyclic graph (DAG).</p>
<figure id="attachment_3373" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png"><img class="size-full wp-image-3373" title="Topological Sort. Directed Graph." src="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png" alt="Topological Sort. Directed Graph." width="620" height="399" srcset="/wp-content/uploads/2012/10/1.-TS-Directed-Graph.png 620w, /wp-content/uploads/2012/10/1.-TS-Directed-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In order to sort a graph using topological sort we need this graph to be acyclic and directed!</figcaption></figure>
<p>Why we don’t what a cycle in the graph? The answer of this question is simple and obvious. In case of cyclic graph, we wouldn’t be able to determine the priority of task execution, thus we won’t be able to sort the tasks properly.</p>
<p>Now the solution we want is to sort the vertices of the graph in some order so for each edge (u, v) u will precede v. Then we&#8217;ll have a linear order of all tasks and by starting their execution we’ll know that everything will be OK.</p>
<figure id="attachment_3372" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png"><img src="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png" alt="Topological Sort. Sort the vertices." title="Topological Sort. Sort the vertices." width="620" height="399" class="size-full wp-image-3372" srcset="/wp-content/uploads/2012/10/2.-TS-Sort-the-vertices.png 620w, /wp-content/uploads/2012/10/2.-TS-Sort-the-vertices-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The output of topological sort should be a list of vertices!</figcaption></figure>
<p>This kind of sort is also known as “topological” sort (or topsort) and it is one of the very basic graph algorithms.<span id="more-3367"></span></p>
<h2>Overview</h2>
<p>OK, so we have an acyclic directed graph, how do we proceed to get a linked list with all the vertices sorted? Since it’s an acyclic graph we know that there is at least one vertex without predecessor. Thus at first place, we can put all the vertices without predecessors into our linked list.</p>
<figure id="attachment_3371" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-TS-First-Step.png"><img src="/wp-content/uploads/2012/10/3.-TS-First-Step.png" alt="Topological Sort. First Step." title="Topological Sort. First Step." width="620" height="399" class="size-full wp-image-3371" srcset="/wp-content/uploads/2012/10/3.-TS-First-Step.png 620w, /wp-content/uploads/2012/10/3.-TS-First-Step-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Initially we get only the vertices without a predecessor!</figcaption></figure>
<p>This approach answers the question – is there a possibility to have more than one valid topological sort of a graph? Indeed, the only thing we’d like to do is to put all the vertices in the correct order, but since there might be vertices with no predecessors any combination of them will be a valid topological sort for a graph.</p>
<p>As we can see from the picture above even for vertices with predecessors our topological sort can vary. Thus [9, 6, 2, 7, 4, 1] is a valid topological sorted graph, but [6, 9, 2, 7, 4, 1] is also a valid topological sort out of the same graph!</p>
<p>Now we can generalize the algorithm in some basic steps.</p>
<p>1. Make an empty list L and an empty list S;<br />
2. Put all the vertices with no predecessors in L;<br />
3. While L has items in it;<br />
    3.1. Pop an item from L – n, and push it to S;<br />
    3.2. For each vertex m adjacent to n;<br />
         3.2.1. Remove (n, m);<br />
	 3.2.2. If m has no predecessors – push it to L;</p>
<figure id="attachment_3370" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/4.-TS-Second-Step.png"><img src="/wp-content/uploads/2012/10/4.-TS-Second-Step.png" alt="Topological Sort. Second Step." title="Topological Sort. Second Step." width="620" height="399" class="size-full wp-image-3370" srcset="/wp-content/uploads/2012/10/4.-TS-Second-Step.png 620w, /wp-content/uploads/2012/10/4.-TS-Second-Step-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The image above explains step 3.2. from the algorithm!</figcaption></figure>
<h2>Code</h2>
<p>Here’s the very basic <a href="/category/php/" title="PHP on stoimen.com">PHP</a> implementation. As you can see the short implementation shows us how easy this algorithm is. However its importance to computer science and programming is enormous.</p>
<pre lang="PHP">
class G
{
    protected $_g = array(
        array(0, 1, 1, 0, 0, 0, 0),
        array(0, 0, 0, 1, 0, 0, 0),
        array(0, 0, 0, 0, 1, 0, 0),
        array(0, 0, 0, 0, 1, 0, 0),
        array(0, 0, 0, 0, 0, 0, 1),
        array(0, 0, 0, 0, 0, 0, 1),
        array(0, 0, 0, 0, 0, 0, 0),
    );
    protected $_list = array();
    protected $_ts   = array();
    protected $_len  = null;
    
    public function __construct()
    {
        $this->_len = count($this->_g);
        
        // finds the vertices with no predecessors
        $sum = 0;
        for ($i = 0; $i < $this->_len; $i++) {
            for ($j = 0; $j < $this->_len; $j++) {
                $sum += $this->_g[$j][$i];
            }
            
            if (!$sum) {
                // append to list
                array_push($this->_list, $i);
            }
            $sum = 0;
        }
    }
    
    public function topologicalSort() 
    {
        while ($this->_list) {
            $t = array_shift($this->_list);
            array_push($this->_ts, $t);
            
            foreach ($this->_g[$t] as $key => $vertex) {
                if ($vertex == 1) {
                    $this->_g[$t][$key] = 0;
                    
                    $sum = 0;
                    for ($i = 0; $i < $this->_len; $i++) {
                        $sum += $this->_g[$i][$key];
                    }
                    
                    if (!$sum) {
                        array_push($this->_list, $key);
                    }
                }
                $sum = 0;
            }
        }
        
        print_r($this->_ts);
    }
}

$g = new G();
/*
Array
(
    [0] => 0
    [1] => 5
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 4
    [6] => 6
)*/
$g->topologicalSort();
</pre>
<h2>Application</h2>
<p>As I already mentioned above this algorithm is practically used to sort the execution of different tasks that depend on each other. However this isn’t its only use. Actually any kind of objects that depend on each other can be modeled with a graph. Indeed sometimes these graphs may be a trees, but most of the cases that isn’t true.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" rel="bookmark" title="Computer Algorithms: Topological Sort Revisited">Computer Algorithms: Topological Sort Revisited </a></li>
<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/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>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/01/computer-algorithms-topological-sort-of-a-graph/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graph Best-First Search</title>
		<link>/2012/09/24/computer-algorithms-graph-best-first-search/</link>
		<comments>/2012/09/24/computer-algorithms-graph-best-first-search/#comments</comments>
		<pubDate>Mon, 24 Sep 2012 10:44:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Algebraic graph theory]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[graph traversal algorithms]]></category>
		<category><![CDATA[Hopcroft–Karp algorithm]]></category>
		<category><![CDATA[Matching]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Path decomposition]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[two algorithms]]></category>
		<category><![CDATA[typical greedy algorithm]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3347</guid>
		<description><![CDATA[Introduction So far we know how to implement graph depth-first and breadth-first search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal. In the examples so &#8230; <a href="/2012/09/24/computer-algorithms-graph-best-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Best-First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </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>
<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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>So far we know how to implement graph <a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" title="Computer Algorithms: Graph Depth-First Search">depth-first</a> and <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" title="Computer Algorithms: Graph Breadth First Search">breadth-first</a> search. These two approaches are crucial in order to understand graph traversal algorithms. However they are just explaining how we can walk through in breadth or depth and sometimes this isn&#8217;t enough for an efficient solution of graph traversal.</p>
<p>In the examples so far we had an undirected, unweighted graph and we were using adjacency matrices to represent the graphs. By <a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" title="Computer Algorithms: Graphs and their Representation">using adjacency matrices</a> we store <strong>1</strong> in the A[i][j] if there’s an edge between vertex i and vertex j. Otherwise we put a <strong>0</strong>. However the value of <strong>1</strong> gives us only the information that we have an edge between two vertices, which is not always enough when designing graphs.</p>
<p>Indeed graphs can be weighted. Sometimes the path between two vertices can have a value. Thinking of a road map we know that distances between cities are represented in miles or kilometers. Thus often representing a road map as a graph, we don’t put just 1 between city A and city B, to say that there is a path between them, but also we put some meaningful information – let’s say the distance in miles between A and B. </p>
<p>Note that this value can be the distance in miles, but it can be something else, like the time in hours we’ve to walk between those two cities. In general this value is a function of A and B. So if we keep the distance between A and B we can say this function is F(A, B) = X, or distance(A, B) = X miles.</p>
<p>Of course in this particular example F(A, B) = F(B, A), but this isn’t always true in practice. We can have a directed graph where F(A, B) != F(B, A).</p>
<p>Here I talk about distance between two cities and it is the edge that brings some additional information. However sometimes we have to store the value of the vertices. Let&#8217;s say I&#8217;m playing a game (like chess) and each move brings me some additional benefit. So each move (vertex) can be evaluated with some particular value. Thus sometimes we don&#8217;t have a function of and edge like F(A, B), but function of the vertices, like F(A) and F(B).</p>
<p>In breadth-first search and depth-first search we just pick up a vertex and we consecutively walk through all its successors that haven’t been visited yet.</p>
<figure id="attachment_3357" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png"><img src="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png" alt="Walk Through an Unweithed Graph" title="Unweithed Graph Walkthrough" width="620" height="399" class="size-full wp-image-3357" srcset="/wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough.png 620w, /wp-content/uploads/2012/09/1.-Unweithed-Graph-Walkthrough-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In order to walk through an unweithed graph using DFS, we chose consecutively each successor of node i!</figcaption></figure>
<p>So in DFS in particular we started from left to right in the array above. So the first node that has to be explored is vertex “1”.</p>
<pre lang="PHP">
0: [0, 1, 0, 0, 1, 1]
</pre>
<p>However sometimes, as I said above, we have weighted graphs, so the question is – is there any problem, regarding to the algorithm speed, if we go consecutively through all successors. The answer in general is yes, so we must modify a bit our code in order to continue not with the first but with the best matching successor. By best-matching we mean that the successor should match some criteria like – minimal or maximal value.<span id="more-3347"></span></p>
<h2>Overview</h2>
<p>In the following example we see that some of the successors of vertex 0 are very far from it, while others are closer. Thus 4 has the value of 5, while node 1’s value is 2 and 5 is 1.</p>
<figure id="attachment_3359" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png"><img src="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png" alt="DFS and Weighted Graph" title="DFS and Weighted Graph" width="620" height="399" class="size-full wp-image-3359" srcset="/wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph.png 620w, /wp-content/uploads/2012/09/2.-BFS-and-Weighted-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Weithed graph brings us more information about the successors of a given vertex. Thus we have to chose carefully which one to get first in our path exploration!</figcaption></figure>
<pre lang="PHP">
0: [0, 2, 0, 0, 5, 1]
</pre>
<p>In this case if we’re searching for the shortest path between 1 and 3, although 1 and 4 are the first two successors in the adjacency matrix of the &#8220;start&#8221; vertex, we don&#8217;t choose them since there’s a better solution – going through node 5.</p>
<figure id="attachment_3360" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/3.-Best-First-Search.png"><img src="/wp-content/uploads/2012/09/3.-Best-First-Search.png" alt="Best-First Search" title="Best-First Search" width="620" height="399" class="size-full wp-image-3360" srcset="/wp-content/uploads/2012/09/3.-Best-First-Search.png 620w, /wp-content/uploads/2012/09/3.-Best-First-Search-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In best-first search we continue the path to the target through the best-matching successor!</figcaption></figure>
<h3>Problems</h3>
<p>The question is – are we sure that by choosing node 5, we’ll find the best path? Even more! Is there a path through node 5? As we see on the image below both cases are possible.</p>
<figure id="attachment_3361" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/4.-BFS-problems.png"><img src="/wp-content/uploads/2012/09/4.-BFS-problems.png" alt="BFS problems" title="BFS problems" width="620" height="399" class="size-full wp-image-3361" srcset="/wp-content/uploads/2012/09/4.-BFS-problems.png 620w, /wp-content/uploads/2012/09/4.-BFS-problems-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Somtimes best-first search doesn&#8217;t find the &#8220;best&#8221; (shortest/longest/cheapest) path to the target!</figcaption></figure>
<p>Practically best-first search is identical with depth-first search, with the main difference that we choose the best-matching successor instead of choosing the first matching successor. So we’re sure that we’re going through all the successors but in some particular order, different from DFS. Thus we know that if there’s a path we’ll find it.</p>
<p>However even if we find the path between A and B, we can’t be sure that there is not a better path. We only know that this path is the best so far. </p>
<p>Another question is – how can we find the best matching successor effectively. Well if we’re looking for the minimal or maximal value one possible solution is to sort the array of successors.</p>
<figure id="attachment_3363" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png"><img src="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png" alt="Using Priority Queues" title="Using Priority Queues" width="620" height="412" class="size-full wp-image-3363" srcset="/wp-content/uploads/2012/09/5.-Using-Priority-Queues.png 620w, /wp-content/uploads/2012/09/5.-Using-Priority-Queues-300x199.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The difference between depth-first and best-first is that we change the order of chosing the next successor!</figcaption></figure>
<pre lang="PHP">
0: [0 => 0, 1 => 2, 2 => 0, 3 => 0, 4 => 5, 5 => 1]
// sorted by value
0: [5 => 1, 1 => 2, 4 => 5, 0 => 0, 2 => 0, 3 => 1]
</pre>
<p>Another good approach will be to use priority queues or heaps.</p>
<p>Thus on every step we’ll get the best matching successor.</p>
<h2>Code</h2>
<p>In general best-first search uses the ground of depth-first search, so its implementation isn&#8217;t more difficult! The following PHP code snippet shows the very small difference between these two algorithms.</p>
<pre lang="PHP">
class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();
    
    public function __construct()
    {
        $this->_g = array(
            array(0, 2, 0, 0, 5, 1),
            array(1, 0, 3, 0, 0, 0),
            array(0, 2, 0, 8, 0, 0),
            array(0, 0, 3, 0, 5, 0),
            array(1, 0, 0, 8, 0, 1),
            array(1, 0, 0, 0, 5, 0),
        );
        
        $this->_len = count($this->_g);
        
        $this->_initVisited();
    }
    
    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }
    
    public function bestFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
    
        echo $vertex . "\n";
        
        asort($this->_g[$vertex]);
        
        foreach ($this->_g[$vertex] as $key => $v) {
            if ($v > 0 && !$this->_visited[$key]) {
                $this->bestFirst($key);
            }
        }
    }
}

$g = new Graph();
// 2 1 0 5 4 3
$g->bestFirst(2);
</pre>
<h2>Application</h2>
<p>Best-first search is a typical greedy algorithm. In its principles lies the main greedy approach of chosing the best possible solution so far. It is important to note that depth-first search and breadth-first search are the very basic graph walk through approaches, but they can be also widely extended in order to solve more complex problems.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </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>
<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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/24/computer-algorithms-graph-best-first-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graph Breadth First Search</title>
		<link>/2012/09/10/computer-algorithms-graph-breadth-first-search/</link>
		<comments>/2012/09/10/computer-algorithms-graph-breadth-first-search/#comments</comments>
		<pubDate>Sun, 09 Sep 2012 21:52:49 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Connected component]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph algorithms]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[search start]]></category>
		<category><![CDATA[search walks]]></category>
		<category><![CDATA[Theoretical computer science]]></category>

		<guid isPermaLink="false">/?p=3338</guid>
		<description><![CDATA[Introduction Since we already know how to represent graphs, we can go further for some very simple approaches of walking through them. Passing by all the vertices of a graph is a fundamental technique for most of the graph algorithms, such as finding shortest/longest paths, etc. First thing to note is that graphs are not &#8230; <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Breadth First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Since we already know <a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" title="Computer Algorithms: Graphs and their Representation">how to represent graphs</a>, we can go further for some very simple approaches of walking through them. Passing by all the vertices of a graph is a fundamental technique for most of the graph algorithms, such as finding shortest/longest paths, etc.</p>
<p>First thing to note is that graphs are not trees, in most of the cases, so walking through them can&#8217;t start from a root, as we do with trees. What we must do first is to decide from where to start – in other words &#8211; choosing a starting vertex. </p>
<figure id="attachment_3343" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-BFS-Choosing-a-Starting-Point.png"><img src="/wp-content/uploads/2012/09/1.-BFS-Choosing-a-Starting-Point.png" alt="BFS Choosing a Starting Point" title="BFS Choosing a Starting Point" width="620" height="399" class="size-full wp-image-3343" srcset="/wp-content/uploads/2012/09/1.-BFS-Choosing-a-Starting-Point.png 620w, /wp-content/uploads/2012/09/1.-BFS-Choosing-a-Starting-Point-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">It&#8217;s clear that depending on the starting point we can get different passes through the graph. Thus choosing a starting point can be very important for our algorithm!</figcaption></figure>
<p>After that we need to know how to proceed. There are two approaches mostly known as “breadth first” and “depth first” search. While depth first search start from a vertex and goes as far as possible, then walks back and passes through vertices that haven’t been visited yet, breath first search is an approach of passing through all the neighbors of the node first, and then go to the next level.<br />
<span id="more-3338"></span></p>
<h2>Overview</h2>
<p>We can thing of breadth first search as a “wave” walk through the graph. In other words we go level by level, as shown on the picture below.</p>
<figure id="attachment_3344" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-BFS-Wave.png"><img src="/wp-content/uploads/2012/09/2.-BFS-Wave.png" alt="BFS Wave" title="BFS Wave" width="620" height="399" class="size-full wp-image-3344" srcset="/wp-content/uploads/2012/09/2.-BFS-Wave.png 620w, /wp-content/uploads/2012/09/2.-BFS-Wave-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">For this very specific graph on the picture we can see how breadth first search walks through the graph level by level!</figcaption></figure>
<p>Initially we mark all vertices as unvisited. A common approach is to create an empty queue where we put the vertices level by level, starting with the initial vertex.</p>
<figure id="attachment_3342" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/3.-BFS-Using-a-Queue.png"><img src="/wp-content/uploads/2012/09/3.-BFS-Using-a-Queue.png" alt="BFS Using a Queue" title="BFS Using a Queue" width="620" height="399" class="size-full wp-image-3342" srcset="/wp-content/uploads/2012/09/3.-BFS-Using-a-Queue.png 620w, /wp-content/uploads/2012/09/3.-BFS-Using-a-Queue-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Using a queue is a typical approach for breadth first search! However this requires more space!</figcaption></figure>
<h2>Code</h2>
<p>This simple approach is fairly easy to implement. Here’s the <a href="/category/php/" title="PHP on Stoimen.com">PHP</a> implementation in few lines of code.</p>
<pre lang="PHP">
<?php

$g = array(
    0 => array(0, 1, 1, 0, 0, 0),
    1 => array(1, 0, 0, 1, 0, 0),
    2 => array(1, 0, 0, 1, 0, 0),
    3 => array(0, 1, 1, 0, 1, 0),
    4 => array(0, 0, 0, 1, 0, 1),
    5 => array(0, 0, 0, 0, 1, 0),
);

function init(&$visited, &$graph) 
{
    foreach ($graph as $key => $vertex) {
        $visited[$key] = 0;
    }
}

function breadth_first(&$graph, $start, $visited)
{
    // create an empty queue
    $q = array();
    
    // initially enqueue only the starting vertex
    array_push($q, $start);
    $visited[$start] = 1;
    echo $start . "\n";
    
    while (count($q)) {
        $t = array_shift($q);
        
        foreach ($graph[$t] as $key => $vertex) {
            if (!$visited[$key] && $vertex == 1) {
                $visited[$key] = 1;
                array_push($q, $key);
                echo $key . "\t";
            }
        }
        echo "\n";
    }
}

$visited = array();
init($visited, $g);
breadth_first($g, 2, $visited);
</pre>
<h2>Complexity</h2>
<p>The complexity of this algorithm clearly is O(n<sup>2</sup>).</p>
<h2>Application</h2>
<p>As I said breadth first and depth first searches are used in many practical cases, as finding shortest/minimal paths etc. That is why understanding these basic principles of walking through a graph is crucial for other, more complex, graph algorithms.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Depth-First Search">Computer Algorithms: Graph Depth-First Search </a></li>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/10/computer-algorithms-graph-breadth-first-search/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graphs and their Representation</title>
		<link>/2012/08/31/computer-algorithms-graphs-and-their-representation/</link>
		<comments>/2012/08/31/computer-algorithms-graphs-and-their-representation/#comments</comments>
		<pubDate>Fri, 31 Aug 2012 20:42:25 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Adjacency list]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Algebraic graph theory]]></category>
		<category><![CDATA[France]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Implicit graph]]></category>
		<category><![CDATA[Induced path]]></category>
		<category><![CDATA[Line graph]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Matrices]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[United Kingdom]]></category>

		<guid isPermaLink="false">/?p=3322</guid>
		<description><![CDATA[Introduction Although this post is supposed to be about algorithms I’ll cover more on graphs and their computer representation. I consider this very important, because there are lots of problems solved by using graphs and it is important to understand different types of representation. First of all let’s try to explain what is a graph? &#8230; <a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graphs and their Representation</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </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/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Although this post is supposed to be about algorithms I’ll cover more on graphs and their computer representation. I consider this very important, because there are lots of problems solved by using graphs and it is important to understand different types of representation.</p>
<p>First of all let’s try to explain what is a graph?</p>
<p>A graph is a specific data structure known in the computer science, that is often used to give a model of different kind of problems where a set of objects relate to each other in some way . For instance, trees are mainly used in order to represent a well-structured hierarchy, but that isn’t enough when modeling objects of the same type. Their relation isn’t always hierarchical! A typical example of graph is a geo map, where we have cities and the roads connecting them. In fact most of the problems solved with graphs relate to finding the shortest or longest path.</p>
<p>Although this is one very typical example actually a huge set of problems is can be solved by using graphs.</p>
<figure id="attachment_3332" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/1.-Graph-Tree.png"><img class="size-full wp-image-3332" title="Graph &amp; Tree" src="/wp-content/uploads/2012/08/1.-Graph-Tree.png" alt="Graph &amp; Tree" width="620" height="399" srcset="/wp-content/uploads/2012/08/1.-Graph-Tree.png 620w, /wp-content/uploads/2012/08/1.-Graph-Tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p><span id="more-3322"></span></p>
<p>As shown on the image above the graph is a “more complex” data structure than the ordinary tree. Thus a graph supports cycles, while the tree doesn’t. In the other hand the nodes of a tree are defined by their parents and children, while in a graph that isn’t true.</p>
<p>In this case each graph is defined by its edges and its vertices. In most of the cases, in order to model and solve our problem, we can assume that the vertices are consecutive numbers starting from (1, or 0 in case of 0 based arrays, as we will see later).</p>
<p>As we see each tree is a graph, but not every graph is a tree.</p>
<p>In first place we must now that graphs can be divided in several categories.</p>
<p>They can be undirected and directed. An undirected graph means that in case there is an edge between the nodes i and j we shell assume that there is a path from i to j, as well as from j to i. In the case of directed graph, we’ll assume that if (i,j) exists there only path from node i to node j and there’s no path between j and i.</p>
<figure id="attachment_3331" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/2.-Directed-Graph.png"><img class="size-full wp-image-3331" title="Directed Graph" src="/wp-content/uploads/2012/08/2.-Directed-Graph.png" alt="Directed Graph" width="620" height="399" srcset="/wp-content/uploads/2012/08/2.-Directed-Graph.png 620w, /wp-content/uploads/2012/08/2.-Directed-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>In this example we assume that all the edges are the same, which in practice isn’t always true. Taking a look back to the example of cities and roads, we know that the roads between different cities are different. In many cases their length in kilometers or miles are defining the algorithm (for instance longest/shortest path). To model this we can use weighted graphs, where each edge is associated with a weight. Note that, in the example below, the weight can be even a negative number. Of course in the example of cities and road that can’t be true, because we can’t have negative distance, but in some cases (let’s say where the path saves us some money) we can have negative values.</p>
<figure id="attachment_3330" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/3.-Weithened-Graph.png"><img class="size-full wp-image-3330" title="Weithened Graph" src="/wp-content/uploads/2012/08/3.-Weithened-Graph.png" alt="Weithened Graph" width="620" height="399" srcset="/wp-content/uploads/2012/08/3.-Weithened-Graph.png 620w, /wp-content/uploads/2012/08/3.-Weithened-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>To complete the whole image, let’s give another example which will make the difference between graphs and trees even bigger. Graphs can be connected and disconnected. This means that the graph is constructed out of two or more sub-graphs without a path between these components. You can think of a disconnected graph as for the roads of the UK and France, since they aren’t connected by land.</p>
<figure id="attachment_3329" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/4.-Connected-Graph.png"><img class="size-full wp-image-3329" title="Connected Graph" src="/wp-content/uploads/2012/08/4.-Connected-Graph.png" alt="Connected Graph" width="620" height="399" srcset="/wp-content/uploads/2012/08/4.-Connected-Graph.png 620w, /wp-content/uploads/2012/08/4.-Connected-Graph-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Overview</h2>
<p>We know what a graph is in general. However we need an appropriate way to represent them in our programs.</p>
<p>There are many type of representation, which can be very useful in some cases and very useless in others. Two of the mostly used types of representation are the <strong>adjacency matrix</strong> and the <strong>adjacency list</strong>.</p>
<h3>Adjacency Matrix</h3>
<p>In the first case we store a matrix (two-dimensional array) with size NxN, where N is the number of vertices. This means that for each edge between the vertices i and j we have the value of 1 (A[i][j] = 1), and 0 otherwise.</p>
<figure id="attachment_3328" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/5.-Undirected-Graph-Adjacency-Matrix.png"><img class="size-full wp-image-3328" title="Undirected Graph &amp; Adjacency Matrix" src="/wp-content/uploads/2012/08/5.-Undirected-Graph-Adjacency-Matrix.png" alt="Undirected Graph &amp; Adjacency Matrix" width="620" height="399" srcset="/wp-content/uploads/2012/08/5.-Undirected-Graph-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/08/5.-Undirected-Graph-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>In case of directed graph, we can use 1 for the edge (i,j) and -1 for (j,i) in case the edge is directed from i to j.</p>
<figure id="attachment_3327" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/6.-Directed-Graph-Adjacency-Matrix.png"><img class="size-full wp-image-3327" title="Directed Graph &amp; Adjacency Matrix" src="/wp-content/uploads/2012/08/6.-Directed-Graph-Adjacency-Matrix.png" alt="Directed Graph &amp; Adjacency Matrix" width="620" height="399" srcset="/wp-content/uploads/2012/08/6.-Directed-Graph-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/08/6.-Directed-Graph-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>For a weighted directed graph we can put the weights instead of 1s.</p>
<figure id="attachment_3326" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/7.-Weighted-Graph-Adjacency-Matrix.png"><img class="size-full wp-image-3326" title="Weighted Graph &amp; Adjacency Matrix" src="/wp-content/uploads/2012/08/7.-Weighted-Graph-Adjacency-Matrix.png" alt="Weighted Graph &amp; Adjacency Matrix" width="620" height="399" srcset="/wp-content/uploads/2012/08/7.-Weighted-Graph-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/08/7.-Weighted-Graph-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>Adjacency Lists</h3>
<p>Another useful representation of graphs are the adjacency lists. In this case for each vertex we store a linked lists consisting of all of his successors.</p>
<figure id="attachment_3325" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/8.-Directed-Graph-Adjacency-List.png"><img class="size-full wp-image-3325" title="Directed Graph &amp; Adjacency List" src="/wp-content/uploads/2012/08/8.-Directed-Graph-Adjacency-List.png" alt="Directed Graph &amp; Adjacency List" width="620" height="399" srcset="/wp-content/uploads/2012/08/8.-Directed-Graph-Adjacency-List.png 620w, /wp-content/uploads/2012/08/8.-Directed-Graph-Adjacency-List-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>Although these two ways are the mostly used, there are also some other type of representations. Such a useful representation is storing only the connectivity between two vertices i and j only if there’s a path between them. Of course this can help us answer the question “is there a path between i and j” in O(1), but unfortunately we lose the information about the graph and we can&#8217;t build it again out of this representation.</p>
<h2>Complexity</h2>
<p>Most of the basic operations in a graph are:</p>
<ol>
<li>Adding an edge;</li>
<li>Deleting an edge;</li>
<li>Answering the question “is there an edge between i and j&#8221;;</li>
<li>Finding the successors of a given vertex;</li>
<li>Finding (if exists) a path between two vertices;</li>
</ol>
<p>Thus depending on the representation these operations can have different complexities. In case that we’re using <strong>adjacency matrix</strong> we have:</p>
<ol>
<li>Adding an edge &#8211; O(1);</li>
<li>Deleting an edge &#8211; O(1);</li>
<li>Answering the question “is there an edge between i and j” &#8211; O(1);</li>
<li>Finding the successors of a given vertex &#8211; O(n);</li>
<li>Finding (if exists) a path between two vertices – O(n<sup>2</sup>);</li>
</ol>
<p>While for an <strong>adjacency list</strong> we can have:</p>
<ol>
<li>Adding an edge – O(log(n));</li>
<li>Deleting an edge – O(log(n));</li>
<li>Answering the question “is there an edge between i and j” – O(log(n));</li>
<li>Finding the successors of a given vertex – O(k), where &#8220;k&#8221; is the length of the lists containing the successors of i;</li>
<li>Finding (if exists) a path between two vertices – O(n+m) – where m &lt;= n;</li>
</ol>
<p>We now see that depending of the representation of the graph we can have different complexities for the same operations. This is very important while trying to solve a problem and can be crucial while chosing the algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </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/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/08/31/computer-algorithms-graphs-and-their-representation/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
