<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vivek Sonani on Medium]]></title>
        <description><![CDATA[Stories by Vivek Sonani on Medium]]></description>
        <link>https://medium.com/@viveksonani22?source=rss-2d92fd48f2f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fGEBnNBmg_fQQ2qh.jpg</url>
            <title>Stories by Vivek Sonani on Medium</title>
            <link>https://medium.com/@viveksonani22?source=rss-2d92fd48f2f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:19:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viveksonani22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Topological Sorting using Source removal algorithm]]></title>
            <link>https://medium.com/@viveksonani22/topological-sorting-using-source-removal-algorithm-6df515c956e0?source=rss-2d92fd48f2f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6df515c956e0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[details]]></category>
            <category><![CDATA[algo]]></category>
            <category><![CDATA[example]]></category>
            <dc:creator><![CDATA[Vivek Sonani]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 12:18:44 GMT</pubDate>
            <atom:updated>2019-09-02T12:18:44.154Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is topological sorting?</strong></p><p>A <strong>topological sort</strong> or <strong>topological ordering</strong> of a <a href="https://en.wikipedia.org/wiki/Directed_graph">directed graph</a> is a <a href="https://en.wikipedia.org/wiki/Total_order">linear ordering</a> of its <a href="https://en.wikipedia.org/wiki/Vertex_(graph_theory)">vertices</a> such that for every directed edge <em>uv</em> from vertex <em>u</em> to vertex <em>v</em>, <em>u</em> comes before <em>v</em> in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another.</p><p>For example, a topological sorting of the following graph is “5 4 2 3 1 0?. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 0 3 1″. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*TjEi6edCZVK1lxEH.png" /></figure><p><strong>Source Removal Algorithm:</strong></p><p>This is a direct implementation of the decrease and conquers method. Following are the steps to be followed in this algorithm-</p><ol><li>From a given graph find a vertex with no incoming edges. Delete it among with all the edges outgoing from it. If there are more than one such vertices then break the tie randomly.</li><li>Note the vertices that are deleted.</li><li>All these recorded vertices give a topologically sorted list.</li></ol><p><strong>Question:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ykfLlQdqXpgcXNn2kjKXg.png" /></figure><p><strong>Answer:</strong></p><p>Choose vertex B, because it has no incoming edge, delete it along with its adjacent edges.</p><p>According to the above steps remove the nodes and put it into a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwPYNm4L7WZwBtYMtJ0YiA.png" /></figure><p>Hence the list after topological sorting will be B, A, D, C, E.</p><p><strong>How to find in-degree of each node?</strong><br>There are 2 ways to calculate in-degree of every vertex:<br>Take an in-degree array which will keep track of<br><strong>1)</strong> Traverse the array of edges and simply increase the counter of the destination node by 1.</p><pre>for each node in Nodes<br>    indegree[node] = 0;<br>for each edge(src,dest) in Edges<br>    indegree[dest]++</pre><p>Time Complexity: O(V+E)</p><p><strong>2)</strong> Traverse the list for every node and then increment the in-degree of all the nodes connected to it by 1.</p><pre>for each node in Nodes<br>        If (list[node].size()!=0) then<br>        for each dest in list<br>            indegree[dest]++;</pre><p>Time Complexity: The outer for loop will be executed V number of times and the inner for loop will be executed E number of times, Thus overall time complexity is O(V+E).</p><p>The overall time complexity of the algorithm is O(V+E)</p><p>Reference: <a href="https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/">https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6df515c956e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Queens Problem using backtracking]]></title>
            <link>https://medium.com/@viveksonani22/4-queens-problem-using-backtracking-632b9f3d6620?source=rss-2d92fd48f2f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/632b9f3d6620</guid>
            <category><![CDATA[solutions]]></category>
            <dc:creator><![CDATA[Vivek Sonani]]></dc:creator>
            <pubDate>Sun, 01 Sep 2019 06:42:43 GMT</pubDate>
            <atom:updated>2019-09-01T06:42:43.591Z</atom:updated>
            <content:encoded><![CDATA[<p>The <em>4-Queens Problem</em><a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#see-what-n-queens-problem-really-is">[1]</a> consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal.</p><p>The following figure illustrates a solution to the 4-Queens Problem: none of the 4 queens can capture each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/0*mYbr18ikMxuT-8A-.png" /></figure><p>Although this particular problem isn’t very impressive, keep in mind that you can generalize it to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*DNGcwkThh3mxxWY_.png" /></figure><p>chessboards with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*FbIIrxhpWKxhCQ0I.png" /></figure><h3>1.1.2. A mathematical translation of the problem</h3><p>In Constraint Programming, we translate a real problem into a <em>mathematical model</em> with <em>variables</em> and <em>constraints</em>. Variables represent decisions and constraints restrain the variables from taking arbitrary values. For instance, to model the 4-Queens Problem , We need several constraints to model that no two queens can capture each other. To limit the number of queens to 4, we can add the following constraint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/0*o5wA9Bo0kKmD2NT1.png" /></figure><p>This constraint ensures that we place 4 queens on the chessboard. In general, constraints only permit possible combinations of values of variables corresponding to real solutions<a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#model-more-complicated-than-that">[2]</a>.</p><p>In the next section, we will see how the <strong>or-tools</strong>‘ CP solver tries to solve this problem. More precisely, how the solver will try to solve the model we will develop and explain in the sections <a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/search_primitives/nqueens.html#nqueen-problem"><em>The n-Queens Problem</em></a> and <a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/search_primitives/basic_model_implementation.html#nqueen-implementation-basic-model"><em>Implementation of a basic model</em></a><a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#dont-need-to-know-model">[3]</a>.</p><h3>1.1.3. Propagation and search</h3><p>Constraints Programming solvers are mainly based on two concepts<a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#constraint-programming-poor-def">[4]</a>:</p><ul><li><strong>propagation</strong><a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#propagation-also-called">[5]</a>: variables can have different values but the solver must remove some of those values to keep all the variables values compatible with the model. In Constraint Programming, clever algorithms are devised to remove those values in an efficient manner. These algorithms <em>propagate</em> the current state of the solver and removes incompatible or undesirable values.</li><li><strong>backtracking</strong>: from time to time, the solver is stuck because it tried to assign some values to some variables that are just not possible (or desirable) because they don’t respect the constraints. The solver must then challenge its previous choices and try other values. This is called <em>backtracking</em>. Backtracking also occurs when the solver finds a solution but continues the search and tries to find another solution.</li></ul><p>To better understand Constraint Programming, let’s have a look at a real solving process<a href="https://acrogenesis.com/or-tools/documentation/user_manual/manual/introduction/4queens.html#real-process-details">[6]</a>. In the following Figures, crosses represent the action of removing values from variables’ domain. Each step in the solving process is separated from the following one by an horizontal line.</p><p>The solver starts by placing the first queen in the upper left corner. Because of the model we gave to the solver, it knows that there cannot be any other queen in the same column, hence the gray crosses on the following Figure. One constraint tells the solver that there cannot be another queen on the same diagonal with a negative slope (the diagonals going down then right). The red crosses show this impossibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*eCfUMfav5_U6jUAH.png" /></figure><p>One constraint tells the solver that no two queens can be on the same row, hence the next red crosses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*WFyn32drHa8F2PHh.png" /></figure><p>After this first step, only the white squares are still available to place the three remaining queens. The process of excluding some squares is what is called <em>propagation</em>.</p><p>The second step starts with the solver trying to place a second queen. It does so in the first available square from the top in the second column. As in the first step, the solver knows that no other queen can be placed in a column where it just placed a queen, hence the new gray crosses in the next Figure.</p><p>The propagation is as follow:</p><p>The same negative diagonal constraint as in step 1 tells the solver that no queen can be on the negative diagonal of the second queen, hence the red cross.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*Hy37jZAW8gs_u2up.png" /></figure><p>Another constraint for the diagonals with positive slopes (diagonals going up then right) tells the solver that no queen can be placed on the positive diagonal of second queen, hence the red cross.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*BpYI_ywCT_jBsZUp.png" /></figure><p>Now, we have a failure as there is no possibility to place a third queen in the third column: there simply can not be a solution with this configuration. The solver has to backtrack!</p><p>The solver decides to challenge its last decision to place the second queen in the third row from the top and places it in the fourth row.</p><p>The propagation is as follow:</p><p>First, the square with the red cross is removed because of the positive diagonal constraint. This leaves only one possibility to place a queen in the fourth column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*4oiz_-etyvL1a3QZ.png" /></figure><p>The “no two queen on the same row” constraint removes one more square in the third column, leaving only one square to place the last remaining queen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*-G2Xh-rv-aIGW1Kw.png" /></figure><p>This is of course not possible and the negative diagonal constraint tells the solver that no queen can be on a negative diagonal from the fourth queen. Since there <strong>is</strong> one, the solver concludes that there is a failure. It has to backtrack again!</p><p>First, it tries to challenge its last choice for the second queen but it detects that there are no more other choices. The solver has to challenge its first choice to place the first queen in the first row and places the first queen in the first column second row.</p><p>The propagation can now take place:</p><p>Two values are taken away because of the negative diagonal constraint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*bJ3380vj5fjPo65c.png" /></figure><p>while the positive diagonal constraint one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*slZtfxclgG6UBo4j.png" /></figure><p>Now comes the turn of the “no two queens on the same row” constraint and it is responsible for removing the next three squares marked by red crosses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*1Jz3o_mAylP0Vu7b.png" /></figure><p>The positive diagonal constraint kicks in and forbids the red square leaving no choice to place a third queen in the third column first row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*IqoCs2aryM3DT3_n.png" /></figure><p>The “no two queens on the same row” constraint forbids any other queen to be placed on the fourth row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*hqDmq691kD96A-Q2.png" /></figure><p>and any other queen on the first row, leaving no choice but to place the fourth queen in the fourth column third row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*9A48uqRjBoxT0t8L.png" /></figure><p>The solver finds out that the model is respected, so we have our first solution! Should the solver continue the search, it would have to backtrack and try to place the first queen in the first column third row.</p><p><strong>Algorithm:</strong></p><h4><strong>private</strong> <strong>static</strong> <strong>boolean</strong> isSafePlace(<strong>int</strong> column, <strong>int</strong> Qi, <strong>int</strong>[] board) {</h4><h4>//check for all previously placed queens</h4><h4><strong>for</strong> (<strong>int</strong> i = 0; i &lt; Qi; i++) {</h4><h4><strong>if</strong> (board[i] == column) { // the ith Queen(previous) is in same column</h4><h4><strong>return</strong> <strong>false</strong>;</h4><h4>}</h4><h4>//the ith Queen is in diagonal</h4><h4>//(r1, c1) - (r2, c1). if |r1-r2| == |c1-c2| then they are in diagonal</h4><h4><strong>if</strong> (Math.abs(board[i] - column) == Math.abs(i - Qi)) {</h4><h4><strong>return</strong> <strong>false</strong>;</h4><h4>}</h4><h4>}</h4><h4><strong>return</strong> <strong>true</strong>;</h4><h4>}</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632b9f3d6620" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>