<?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>basic graph algorithms &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/basic-graph-algorithms/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 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>
	</channel>
</rss>
