{"id":25603,"date":"2017-10-15T20:20:32","date_gmt":"2017-10-15T14:50:32","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25603"},"modified":"2017-10-15T20:20:32","modified_gmt":"2017-10-15T14:50:32","slug":"java-programming-backtracking-set-3-n-queen-problem","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-backtracking-set-3-n-queen-problem\/","title":{"rendered":"JAVA Programming-Backtracking Set 3 (N Queen Problem)"},"content":{"rendered":"<p>We have discussed Knight\u2019s tour and Rat in a Maze problems in Set 1 and Set 2 respectively. Let us discuss N Queen as another example problem that can be solved using Backtracking.<\/p>\n<p>The N Queen is the problem of placing N chess queens on an N\u00d7N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem.<\/p>\n<p>The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example following is the output matrix for above 4 queen solution.<\/p>\n<pre>              { 0,  1,  0,  0}\r\n              { 0,  0,  0,  1}\r\n              { 1,  0,  0,  0}\r\n              { 0,  0,  1,  0}<\/pre>\n<p><strong>Naive Algorithm<\/strong><br \/>\nGenerate all possible configurations of queens on board and print a configuration that satisfies the given constraints.<\/p>\n<pre>while there are untried conflagrations\r\n{\r\n   generate the next configuration\r\n   if queens don't attack in this configuration then\r\n   {\r\n      print this configuration;\r\n   }\r\n}<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Backtracking Algorithm<\/strong><br \/>\nThe idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.<\/p>\n<pre>1) Start in the leftmost column\r\n2) If all queens are placed\r\n    return true\r\n3) Try all rows in the current column.  Do following for every tried row.\r\n    a) If the queen can be placed safely in this row then mark this [row, \r\n        column] as part of the solution and recursively check if placing  \r\n        queen here leads to a solution.\r\n    b) If placing queen in [row, column] leads to a solution then return \r\n        true.\r\n    c) If placing queen doesn't lead to a solution then umark this [row, \r\n        column] (Backtrack) and go to step (a) to try other rows.\r\n3) If all rows have been tried and nothing worked, return false to trigger \r\n    backtracking.<\/pre>\n<p><strong>Implementation of Backtracking solution<\/strong><\/p>\n<p><strong>JAVA Programming<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/* Java program to solve N Queen Problem using<br\/>   backtracking *\/<br\/>public class NQueenProblem<br\/>{<br\/>    final int N = 4;<br\/> <br\/>    \/* A utility function to print solution *\/<br\/>    void printSolution(int board[][])<br\/>    {<br\/>        for (int i = 0; i &lt; N; i++)<br\/>        {<br\/>            for (int j = 0; j &lt; N; j++)<br\/>                System.out.print(&quot; &quot; + board[i][j]<br\/>                                 + &quot; &quot;);<br\/>            System.out.println();<br\/>        }<br\/>    }<br\/> <br\/>    \/* A utility function to check if a queen can<br\/>       be placed on board[row][col]. Note that this<br\/>       function is called when &quot;col&quot; queens are already<br\/>       placeed in columns from 0 to col -1. So we need<br\/>       to check only left side for attacking queens *\/<br\/>    boolean isSafe(int board[][], int row, int col)<br\/>    {<br\/>        int i, j;<br\/> <br\/>        \/* Check this row on left side *\/<br\/>        for (i = 0; i &lt; col; i++)<br\/>            if (board[row][i] == 1)<br\/>                return false;<br\/> <br\/>        \/* Check upper diagonal on left side *\/<br\/>        for (i=row, j=col; i&gt;=0 &amp;&amp; j&gt;=0; i--, j--)<br\/>            if (board[i][j] == 1)<br\/>                return false;<br\/> <br\/>        \/* Check lower diagonal on left side *\/<br\/>        for (i=row, j=col; j&gt;=0 &amp;&amp; i&lt;N; i++, j--)<br\/>            if (board[i][j] == 1)<br\/>                return false;<br\/> <br\/>        return true;<br\/>    }<br\/> <br\/>    \/* A recursive utility function to solve N<br\/>       Queen problem *\/<br\/>    boolean solveNQUtil(int board[][], int col)<br\/>    {<br\/>        \/* base case: If all queens are placed<br\/>           then return true *\/<br\/>        if (col &gt;= N)<br\/>            return true;<br\/> <br\/>        \/* Consider this column and try placing<br\/>           this queen in all rows one by one *\/<br\/>        for (int i = 0; i &lt; N; i++)<br\/>        {<br\/>            \/* Check if queen can be placed on<br\/>               board[i][col] *\/<br\/>            if (isSafe(board, i, col))<br\/>            {<br\/>                \/* Place this queen in board[i][col] *\/<br\/>                board[i][col] = 1;<br\/> <br\/>                \/* recur to place rest of the queens *\/<br\/>                if (solveNQUtil(board, col + 1) == true)<br\/>                    return true;<br\/> <br\/>                \/* If placing queen in board[i][col]<br\/>                   doesn&#039;t lead to a solution then<br\/>                   remove queen from board[i][col] *\/<br\/>                board[i][col] = 0; \/\/ BACKTRACK<br\/>            }<br\/>        }<br\/> <br\/>        \/* If queen can not be place in any row in<br\/>           this colum col, then return false *\/<br\/>        return false;<br\/>    }<br\/> <br\/>    \/* This function solves the N Queen problem using<br\/>       Backtracking.  It mainly uses  solveNQUtil() to<br\/>       solve the problem. It returns false if queens<br\/>       cannot be placed, otherwise return true and<br\/>       prints placement of queens in the form of 1s.<br\/>       Please note that there may be more than one<br\/>       solutions, this function prints one of the<br\/>       feasible solutions.*\/<br\/>    boolean solveNQ()<br\/>    {<br\/>        int board[][] = {{0, 0, 0, 0},<br\/>            {0, 0, 0, 0},<br\/>            {0, 0, 0, 0},<br\/>            {0, 0, 0, 0}<br\/>        };<br\/> <br\/>        if (solveNQUtil(board, 0) == false)<br\/>        {<br\/>            System.out.print(&quot;Solution does not exist&quot;);<br\/>            return false;<br\/>        }<br\/> <br\/>        printSolution(board);<br\/>        return true;<br\/>    }<br\/> <br\/>    \/\/ driver program to test above function<br\/>    public static void main(String args[])<br\/>    {<br\/>        NQueenProblem Queen = new NQueenProblem();<br\/>        Queen.solveNQ();<br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Abhishek Shankhadhar<\/code><\/pre> <\/div>\n<p><strong>Output: The 1 values indicate placements of queens<\/strong><\/p>\n<pre> 0  0  1  0 \r\n 1  0  0  0 \r\n 0  0  0  1 \r\n 0  1  0  0<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>JAVA Programming-Backtracking Set 3 (N Queen Problem) &#8211; JAVA &#8211; discuss N Queen as another example problem that can be solved using Backtracking.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,73907,1,2139],"tags":[74485,74505,74484,74518,74499,74498,74504,74515,74480,74506,74517,74495,74520,74521,74511,70502,73908,74160,74486,74164,74492,74493,74514,74162,74519,74483,74513,74488,74481,74491,74510,74508,74487,74482,74489,74502,74496,73910],"class_list":["post-25603","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-backtracking-algorithm","category-coding","category-java","tag-4-queen-problem-using-backtracking","tag-4-queens-problem","tag-4-queens-problem-using-backtracking-algorithm","tag-8-queen-problem-in-artificial-intelligence","tag-8-queen-problem-solution","tag-8-queen-problem-using-backtracking","tag-8-queens","tag-8-queens-on-a-chessboard","tag-8-queens-problem","tag-8-queens-problem-algorithm","tag-8-queens-problem-algorithm-pdf","tag-8-queens-problem-in-c","tag-8-queens-problem-java-code","tag-8-queens-problem-python","tag-8-queens-problem-using-genetic-algorithm-code","tag-backtrack","tag-backtracking-algorithm","tag-backtracking-algorithm-example","tag-backtracking-algorithm-for-8-queen-problem","tag-backtracking-algorithm-pdf","tag-backtracking-definition","tag-backtracking-in-daa","tag-backtracking-method","tag-backtracking-problems","tag-backtracking-python","tag-chess-problems","tag-chess-two-queens","tag-constraint-satisfaction-problem","tag-cryptarithmetic-problem","tag-cryptarithmetic-problem-solved-examples","tag-eight-queens-problem","tag-n-queens","tag-nxn-six","tag-queen-games","tag-queen-in-chess","tag-queens-problem","tag-sum-of-subset-problem-using-backtracking","tag-what-is-backtracking"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25603","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25603"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25603\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25603"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25603"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25603"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}