{"id":13265,"date":"2023-02-20T08:13:59","date_gmt":"2023-02-20T08:13:59","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=13265"},"modified":"2023-07-20T06:55:36","modified_gmt":"2023-07-20T06:55:36","slug":"how-do-you-solve-the-n-queen-problem","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/","title":{"rendered":"How do you Solve the N Queen Problem?"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\" alt=\"\" \/><\/p>\n<p>The backtracking algorithm is used to solve the N queen problem, in which the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found. At each step, the algorithm checks to see if the newly placed queen conflicts with any previously placed queens, and if so, it backtracks. The process is repeated until all N queens are placed on the board without conflict, or until all possible solutions are exhausted. The resulting board is a correct solution to the N queen problem.<\/p>\n<h2>What is Backtracking?<\/h2>\n<p>Backtracking is a problem-solving technique that involves recursively trying out different solutions to a problem, and backtracking or undoing previous choices when they don&#8217;t lead to a valid solution. It is commonly used in algorithms that search for all possible solutions to a problem, such as the famous eight-queens puzzle. Backtracking is a powerful and versatile technique that can be used to solve a wide range of problems.<\/p>\n<p>Backtracking is often used in constraint satisfaction problems, such as the N Queen problem, where we need to find a solution that satisfies a set of constraints. In these problems, we start by choosing a value for one of the variables and checking if it satisfies the constraints. If it does, we move on to the next variable and repeat the process. If the current value does not satisfy the constraints, we backtrack to the previous variable and try a different value.<\/p>\n<p>Backtracking is an effective technique for solving problems, as it allows us to incrementally build a solution and avoids the need to consider all possible solutions from scratch. However, it can also be time-consuming, as it requires many iterations and checks. To make backtracking more efficient, various optimization techniques, such as constraint propagation and heuristics, can be used.<\/p>\n<h2>What is N Queen Problem Algorithm?<\/h2>\n<p>The N-Queens Problem is a chess puzzle in which N chess queens must be placed on a NxN chessboard so that no two queens threaten each other. It has received extensive research in computer science and mathematics, and it is frequently used as a standard for evaluating algorithms and heuristics. The problem has a long history and practical applications in scheduling, data encryption, and pattern recognition.<\/p>\n<p>For example, the two possible solutions to the 4 Queen problem are shown below:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092695-How%20do%20you%20Solve%20the%20N%20Queen%20Problem1.png\" alt=\"\" \/><\/p>\n<p>The N Queen problem can be solved by using various approaches, such as brute force, backtracking, and genetic algorithms. Backtracking is one of the popular approaches for solving the N Queen problem, and it is simple to implement and can be made more efficient with optimization techniques.<\/p>\n<h2>N-Queen Algorithm<\/h2>\n<p>The complete algorithm for the N queen problem is discussed below : <\/p>\n<ul>\n<li>Start in the leftmost column<\/li>\n<li>If all queens are placed, return true<\/li>\n<li>Try all rows in the current column. For each row:<\/li>\n<li>a. If the queen can be placed safely in this row, mark this cell and recursively try placing the rest of the queen<\/li>\n<li>b. If placing the queen in this row leads to an unsafe configuration, unmark the cell and try the next row<\/li>\n<li>If all rows have been tried and nothing worked, return false to trigger backtracking<\/li>\n<\/ul>\n<h2>Approaches to Solve N Queen Problem<\/h2>\n<p>Below we have discussed approaches to solve the N Queen Problem<\/p>\n<h3>Approach 1: Naive Approach to Solve N Queen Problem<\/h3>\n<p>In this approach, we generate all possible queen configurations on board and print a configuration that satisfies the given constraints.<\/p>\n<p><strong>Below is the pseudo-code for Naive Approach<\/strong><\/p>\n<pre><code>while there are unexplored configurations.\n{\n   generate the next configuration\n   if queens don't attack in this configuration then\n   {\n      print this configuration;\n   }\n}<\/code><\/pre>\n<h3>Approach 2: Solving N Queen Problem using backtracking<\/h3>\n<p>By using backtracking we position queens in different columns one by one, beginning with the leftmost column. When we position a queen in a column, we look for clashes with other queens that have already been placed. If we locate a row in the current column with no collision, we mark this row and column as part of the solution. We backtrack and return false if we cannot discover such a row due to clashes.<\/p>\n<p><strong>Algorithm:<\/strong><br \/>\nHere&#8217;s an algorithm to solve the n queen problem:<\/p>\n<ul>\n<li>Start with an empty chessboard of size n x n.<\/li>\n<li>Place the first queen in the top-left corner of the board (i.e., row 1, column 1).<\/li>\n<li>Move to the next row and try to place a queen in each column until a valid position is found or all columns have been tried.<\/li>\n<li>If a valid position is found, move to the next row and repeat step 3.<\/li>\n<li>If all columns have been tried in the current row without finding a valid position, backtrack to the previous row and move the queen to the next column in that row. Repeat step 3.<\/li>\n<li>If all rows have been tried without finding a solution, backtrack to the previous row and move the queen to the next column in that row. Repeat step 3.<\/li>\n<li>If a solution is found, print the positions of the queens on the board and exit the program.<\/li>\n<\/ul>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_12914 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_12914 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_12914 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_12914 .wpsm_nav-tabs > li.active > a, #tab_container_12914 .wpsm_nav-tabs > li.active > a:hover, #tab_container_12914 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_12914 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_12914 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_12914 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_12914 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_12914 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_12914 .wpsm_nav-tabs > li > a:hover , #tab_container_12914 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_12914 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_12914 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_12914 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_12914 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_12914 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_12914 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_12914 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_12914 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_12914 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_12914 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_12914 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_12914\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_12914\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12914_1\" aria-controls=\"tabs_desc_12914_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12914_2\" aria-controls=\"tabs_desc_12914_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12914_3\" aria-controls=\"tabs_desc_12914_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_12914\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_12914_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\">#include &lt;bits\/stdc++.h&gt;\r\n#define N 4\r\nusing namespace std;\r\n\r\nvoid printBoard(int board[N][N])\r\n{\r\n    for (int i = 0; i &lt; N; i++) {\r\n        for (int j = 0; j &lt; N; j++)\r\n        if(board[i][j])\r\n            cout &lt;&lt; \"Q \";\r\n        else cout&lt;&lt;\". \";\r\n        cout&lt;&lt;endl;\r\n    }\r\n}\r\n\r\nbool isSafe(int board[N][N], int row, int col)\r\n{\r\n    int i, j;\r\n\r\n    for (i = 0; i &lt; col; i++)\r\n        if (board[row][i])\r\n            return false;\r\n\r\n    for (i = row, j = col; i &gt;= 0 &amp;&amp; j &gt;= 0; i--, j--)\r\n        if (board[i][j])\r\n            return false;\r\n\r\n    for (i = row, j = col; j &gt;= 0 &amp;&amp; i &lt; N; i++, j--)\r\n        if (board[i][j])\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\n\/\/ A recursive function to solve N Queen problem\r\nbool solveNQ(int board[N][N], int col)\r\n{\r\n    \/\/ base case\r\n    if (col &gt;= N)\r\n        return true;\r\n\r\n    for (int i = 0; i &lt; N; i++) {\r\n        if (isSafe(board, i, col)) {\r\n            \/* Place this queen in board[i][col] *\/\r\n            board[i][col] = 1;\r\n\r\n            \/* recursively try to place rest of the queens *\/\r\n            if (solveNQ(board, col + 1))\r\n                return true;\r\n\r\n            board[i][col] = 0; \/\/ BACKTRACK\r\n        }\r\n    }\r\n    return false;\r\n}\r\n\r\nbool solve()\r\n{\r\n    int board[N][N] = { { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 } };\r\n\r\n    if (solveNQ(board, 0) == false) {\r\n        cout &lt;&lt; \"No Possible Solution exist\";\r\n        return false;\r\n    }\r\n\r\n    printBoard(board);\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    solve();\r\n    return 0;\r\n}<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_12914_2\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">import java.util.*;\r\nimport java.lang.*;\r\nimport java.io.*;\r\n\r\nclass PrepBytes {\r\n    final int N = 4;\r\n\r\n    void printBoard(int board[][])\r\n    {\r\n        for (int i = 0; i &lt; N; i++) {\r\n            for (int j = 0; j &lt; N; j++)\r\n                if(board[i][j]==1)\r\n                    System.out.print(\"Q \");\r\n                else\r\n                    System.out.print(\". \");\r\n            System.out.println();\r\n        }\r\n    }\r\n\r\n    boolean isSafe(int board[][], int row, int col)\r\n    {\r\n        int i, j;\r\n\r\n        \/* Check this row on left side *\/\r\n        for (i = 0; i &lt; col; i++)\r\n            if (board[row][i] == 1)\r\n                return false;\r\n\r\n        \/* Check upper diagonal on left side *\/\r\n        for (i = row, j = col; i &gt;= 0 &amp;&amp; j &gt;= 0; i--, j--)\r\n            if (board[i][j] == 1)\r\n                return false;\r\n\r\n        \/* Check lower diagonal on left side *\/\r\n        for (i = row, j = col; j &gt;= 0 &amp;&amp; i &lt; N; i++, j--)\r\n            if (board[i][j] == 1)\r\n                return false;\r\n\r\n        return true;\r\n    }\r\n\r\n    boolean solveNQ(int board[][], int col)\r\n    {\r\n        \/\/ base case\r\n        if (col &gt;= N)\r\n            return true;\r\n\r\n        for (int i = 0; i &lt; N; i++) {\r\n            \/* Check if the queen can be placed on\r\n            board[i][col] *\/\r\n            if (isSafe(board, i, col)) {\r\n                \/* Place this queen in board[i][col] *\/\r\n                board[i][col] = 1;\r\n\r\n                \/* recursively try to place rest of the queens *\/\r\n                if (solveNQ(board, col + 1) == true)\r\n                    return true;\r\n\r\n                board[i][col] = 0; \/\/ Backtracking\r\n            }\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    boolean solve()\r\n    {\r\n        int board[][] = { { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 } };\r\n\r\n        if (solveNQ(board, 0) == false) {\r\n            System.out.print(\"No Possible Solution exist\");\r\n            return false;\r\n        }\r\n\r\n        printBoard(board);\r\n        return true;\r\n    }\r\n\r\n    public static void main(String args[])\r\n    {\r\n        PrepBytes Queen = new PrepBytes();\r\n        Queen.solve();\r\n    }\r\n}<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_12914_3\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">global N\r\nN = 4\r\n\r\ndef printBoard(board):\r\n    for i in range(N):\r\n        for j in range(N):\r\n            print(board[i][j], end = \" \")\r\n        print()\r\n\r\ndef isSafe(board, row, col):\r\n\r\n    # Check this row on left side\r\n    for i in range(col):\r\n        if board[row][i] == 1:\r\n            return False\r\n\r\n    # Check upper diagonal on left side\r\n    for i, j in zip(range(row, -1, -1),\r\n                    range(col, -1, -1)):\r\n        if board[i][j] == 1:\r\n            return False\r\n\r\n    # Check lower diagonal on left side\r\n    for i, j in zip(range(row, N, 1),\r\n                    range(col, -1, -1)):\r\n        if board[i][j] == 1:\r\n            return False\r\n\r\n    return True\r\n\r\ndef solveNQ(board, col):\r\n    \r\n    # base case\r\n    if col &gt;= N:\r\n        return True\r\n\r\n    # Consider this column and try placing\r\n    # this queen in all rows one by one\r\n    for i in range(N):\r\n\r\n        if isSafe(board, i, col):\r\n            \r\n            # Place this queen in board[i][col]\r\n            board[i][col] = 1\r\n\r\n            # recursively try to place rest of the queens\r\n            if solveNQ(board, col + 1) == True:\r\n                return True\r\n                \r\n            # backtracking\r\n            board[i][col] = 0\r\n\r\n    return False\r\n\r\ndef solve():\r\n    board = [ [0, 0, 0, 0],\r\n            [0, 0, 0, 0],\r\n            [0, 0, 0, 0],\r\n            [0, 0, 0, 0] ]\r\n\r\n    if solveNQ(board, 0) == False:\r\n        print (\"No Possible Solution exists\")\r\n        return False\r\n\r\n    printBoard(board)\r\n    return True\r\n\r\nsolve()<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_12914 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_12914 a\"),jQuery(\"#tab-content_12914\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Output:<\/strong><\/p>\n<pre><code>. . Q . \nQ . . . \n. . . Q \n. Q . . <\/code><\/pre>\n<p><strong>Time Complexity:<\/strong> O(N * N!)<br \/>\n<strong>Space Complexity:<\/strong> O(N^2)<\/p>\n<p><strong>Dry Run of Approach 2 N Queen Problem<\/strong><br \/>\nLet&#8217;s do a dry run of the N Queen problem for N=4<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092695-How%20do%20you%20Solve%20the%20N%20Queen%20Problem2.png\" alt=\"\" \/><\/p>\n<ol>\n<li>Place the queen in the leftmost column.<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092695-How%20do%20you%20Solve%20the%20N%20Queen%20Problem3.png\" alt=\"\" \/><\/p>\n<ol start=\"2\">\n<li>Place the second queen in the second column such that it cannot attack the queen in the first column.<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092695-How%20do%20you%20Solve%20the%20N%20Queen%20Problem4.png\" alt=\"\" \/><\/p>\n<ol start=\"3\">\n<li>\n<p>Place the third queen in the third column so that it cannot attack the queen in the first two columns. No such placement is possible, so backtrack to the second column.<\/p>\n<\/li>\n<li>\n<p>Place the second queen in another safe cell in the second column.<\/p>\n<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092696-How%20do%20you%20Solve%20the%20N%20Queen%20Problem5.png\" alt=\"\" \/><\/p>\n<ol start=\"5\">\n<li>Place the third queen in a safe cell in the third column. <\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092696-How%20do%20you%20Solve%20the%20N%20Queen%20Problem6.png\" alt=\"\" \/><\/p>\n<ol start=\"6\">\n<li>\n<p>Place the fourth queen in the adjacent columns so that it cannot attack the queen in the first three columns. No such placement is possible, so backtrack to the third column. <\/p>\n<\/li>\n<li>\n<p>Place the third queen in another safe cell in the third column. There is no other safe cell for the queen in column 3, so backtrack.<\/p>\n<\/li>\n<li>\n<p>There is no other safe cell for the queen in column 2, so backtrack to the first column.<\/p>\n<\/li>\n<li>\n<p>Place the first queen in the next safe cell in the first column.<\/p>\n<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092696-How%20do%20you%20Solve%20the%20N%20Queen%20Problem7.png\" alt=\"\" \/><\/p>\n<ol start=\"10\">\n<li>Place the second queen in a safe cell in the second column.<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092716-How%20do%20you%20Solve%20the%20N%20Queen%20Problem8.png\" alt=\"\" \/><\/p>\n<ol start=\"11\">\n<li>Place the third queen in a safe cell in the third column. <\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092717-How%20do%20you%20Solve%20the%20N%20Queen%20Problem9.png\" alt=\"\" \/><\/p>\n<ol start=\"12\">\n<li>\n<p>Place the fourth queen in a safe cell in the fourth column.<\/p>\n<\/li>\n<li>\n<p>Finally, we have our solution!<\/p>\n<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092717-How%20do%20you%20Solve%20the%20N%20Queen%20Problem10.png\" alt=\"\" \/><\/p>\n<h3>Approach 3: Backtracking with optimization<\/h3>\n<p>The reason behind the N queen problem approach is that instead of checking every element in the right and left diagonals, we can use the property of diagonals:<\/p>\n<ol>\n<li>For each right diagonal, the sum of I and j is constant and unique, where i represents row and j represents a column in the chess board.<\/li>\n<li>The difference between i and j is constant and unique for each left diagonal, where i and j represent the row and column of the chess board, respectively.<\/li>\n<\/ol>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_12915 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_12915 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_12915 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_12915 .wpsm_nav-tabs > li.active > a, #tab_container_12915 .wpsm_nav-tabs > li.active > a:hover, #tab_container_12915 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_12915 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_12915 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_12915 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_12915 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_12915 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_12915 .wpsm_nav-tabs > li > a:hover , #tab_container_12915 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_12915 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_12915 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_12915 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_12915 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_12915 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_12915 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_12915 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_12915 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_12915 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_12915 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_12915 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_12915\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_12915\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12915_1\" aria-controls=\"tabs_desc_12915_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>C++<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12915_2\" aria-controls=\"tabs_desc_12915_2\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_12915_3\" aria-controls=\"tabs_desc_12915_3\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_12915\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_12915_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\">#include&lt;bits\/stdc++.h&gt;\r\nusing namespace std;\r\n#define N 4\r\n\/* leftD is an array where its indices indicate row-col+N-1\r\n(N-1) is for shifting the difference to store negative\r\nindices *\/\r\nint leftD[30] = { 0 };\r\n\/* rightD is an array where its indices indicate row+col\r\nand used to check whether a queen can be placed on\r\nright diagonal or not*\/\r\nint rightD[30] = { 0 };\r\n\/*column array where its indices indicates column and\r\nused to check whether a queen can be placed in that\r\nrow or not*\/\r\nint col[30] = { 0 };\r\n\r\nvoid print(int board[N][N])\r\n{\r\n    for (int i = 0; i &lt; N; i++) {\r\n        for (int j = 0; j &lt; N; j++)\r\n            if(board[i][j]==1){\r\n                cout&lt;&lt;\"Q \";\r\n            }\r\n            else{\r\n                cout&lt;&lt;\". \";\r\n            }\r\n        cout&lt;&lt;endl;\r\n    }\r\n}\r\n\r\nbool solveNQ(int board[N][N], int j)\r\n{\r\n    \/\/ base case\r\n    if (j &gt;= N)\r\n        return true;\r\n        \r\n    for (int i = 0; i &lt; N; i++) {\r\n        \/* Here we are checking if a queen can be placed on\r\n        board[row][col]. We just need to check\r\n        left[row-col+n-1] and right[row+coln] where\r\n        left and right are for left and right\r\n        diagonal respectively*\/\r\n        if ((leftD[i - j + N - 1] != 1 &amp;&amp; rightD[i + j] != 1) &amp;&amp; col[i] != 1) {\r\n            board[i][j] = 1;\r\n            leftD[i - j + N - 1] = rightD[i + j] = col[i] = 1;\r\n\r\n            if (solveNQ(board, j + 1))\r\n                return true;\r\n                \r\n            board[i][j] = 0; \/\/ Backtracking\r\n            leftD[i - j + N - 1] = rightD[i + j] = col[i] = 0;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nbool solve()\r\n{\r\n    int board[N][N] = { { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 } };\r\n\r\n    if (solveNQ(board, 0) == false) {\r\n        cout&lt;&lt;\"No Possible Configuration exists\";\r\n        return false;\r\n    }\r\n\r\n    print(board);\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    solve();\r\n    return 0;\r\n}<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_12915_2\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">import java.util.*;\r\n\r\nclass PrepBytes\r\n{\r\n    static int N = 4;\r\n\r\n    \/* ld is an array where its indices indicate row-col+N-1\r\n    (N-1) is for shifting the difference to store negative\r\n    indices *\/\r\n    static int []ld = new int[30];\r\n\r\n    \/* rd is an array where its indices indicate row+col\r\n    and used to check whether a queen can be placed on\r\n    right diagonal or not*\/\r\n    static int []rd = new int[30];\r\n\r\n    \/*column array where its indices indicates column and\r\n    used to check whether a queen can be placed in that\r\n    row or not*\/\r\n    static int []cl = new int[30];\r\n    \r\n    static void printSol(int board[][])\r\n    {\r\n        for (int i = 0; i &lt; N; i++)\r\n        {\r\n            for (int j = 0; j &lt; N; j++)\r\n                System.out.print(board[i][j] + \" \");\r\n            System.out.println();\r\n        }\r\n    }\r\n    \r\n    static boolean solveNQ(int board[][], int col)\r\n    {\r\n        \/\/ base case\r\n        if (col &gt;= N)\r\n            return true;\r\n    \r\n        \/* Consider this column and try placing\r\n        this queen in all rows one by one *\/\r\n        for (int i = 0; i &lt; N; i++)\r\n        {\r\n            \r\n            \/* Check if the queen can be placed on\r\n            board[i][col] *\/\r\n            \/* A check if a queen can be placed on\r\n            board[row][col].We just need to check\r\n            ld[row-col+n-1] and rd[row+coln] where\r\n            ld and rd are for left and right\r\n            diagonal respectively*\/\r\n            if ((ld[i - col + N - 1] != 1 &amp;&amp;\r\n                rd[i + col] != 1) &amp;&amp; cl[i] != 1)\r\n            {\r\n                \/* Place this queen in board[i][col] *\/\r\n                board[i][col] = 1;\r\n                ld[i - col + N - 1] =\r\n                rd[i + col] = cl[i] = 1;\r\n    \r\n                \/* recursively try to place rest of the queens *\/\r\n                if (solveNQ(board, col + 1))\r\n                    return true;\r\n    \r\n                board[i][col] = 0; \/\/ Backtrack\r\n                ld[i - col + N - 1] =\r\n                rd[i + col] = cl[i] = 0;\r\n            }\r\n        }\r\n    \r\n        return false;\r\n    }\r\n    \r\n    static boolean solve()\r\n    {\r\n        int board[][] = {{ 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 },\r\n                        { 0, 0, 0, 0 }};\r\n    \r\n        if (solveNQ(board, 0) == false)\r\n        {\r\n            System.out.printf(\"No Possible Solution exist\");\r\n            return false;\r\n        }\r\n    \r\n        printSol(board);\r\n        return true;\r\n    }\r\n    \r\n    public static void main(String[] args)\r\n    {\r\n        solve();\r\n    }\r\n}<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane \" id=\"tabs_desc_12915_3\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">N = 4\r\n\r\n\"\"\" ld is an array where its indices indicate row-col+N-1\r\n(N-1) is for shifting the difference to store negative\r\nindices \"\"\"\r\nld = [0] * 30\r\n\r\n\"\"\" rd is an array where its indices indicate row+col\r\nand used to check whether a queen can be placed on\r\nright diagonal or not\"\"\"\r\nrd = [0] * 30\r\n\r\n\"\"\"column array where its indices indicates column and\r\nused to check whether a queen can be placed in that\r\n    row or not\"\"\"\r\ncl = [0] * 30\r\n\r\ndef printSol(board):\r\n    for i in range(N):\r\n        for j in range(N):\r\n            print(board[i][j], end = \" \")\r\n        print()\r\n\r\ndef solveNQ(board, col):\r\n    if (col &gt;= N):\r\n        return True\r\n        \r\n    for i in range(N):\r\n        \r\n        \"\"\" Check if the queen can be placed on board[i][col] \"\"\"\r\n        \"\"\" A check if a queen can be placed on board[row][col].\r\n        We just need to check ld[row-col+n-1] and rd[row+coln]\r\n        where ld and rd are for left and right diagonal respectively\"\"\"\r\n        if ((ld[i - col + N - 1] != 1 and\r\n            rd[i + col] != 1) and cl[i] != 1):\r\n                \r\n            \"\"\" Place this queen in board[i][col] \"\"\"\r\n            board[i][col] = 1\r\n            ld[i - col + N - 1] = rd[i + col] = cl[i] = 1\r\n            \r\n            \"\"\" recur to place rest of the queens \"\"\"\r\n            if (solveNQ(board, col + 1)):\r\n                return True\r\n        \r\n            board[i][col] = 0 # Backtrack\r\n            ld[i - col + N - 1] = rd[i + col] = cl[i] = 0\r\n            \r\n    return False\r\n    \r\ndef solve():\r\n    board = [[0, 0, 0, 0],\r\n            [0, 0, 0, 0],\r\n            [0, 0, 0, 0],\r\n            [0, 0, 0, 0]]\r\n    if (solveNQ(board, 0) == False):\r\n        print(\"No Solution exist\")\r\n        return False\r\n    printSol(board)\r\n    return True\r\n    \r\nsolve()<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_12915 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_12915 a\"),jQuery(\"#tab-content_12915\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Output:<\/strong><\/p>\n<pre><code>0 0 1 0 \n1 0 0 0 \n0 0 0 1 \n0 1 0 0 <\/code><\/pre>\n<p><strong>Time Complexity:<\/strong> O(N * N!)<br \/>\n<strong>Space Complexity:<\/strong> O(N)<\/p>\n<p><strong>Conclusion<\/strong><br \/>\nThe N queen problem is a difficult one that can be solved with a backtracking algorithm.  The problem necessitates careful consideration of the rules governing queen placement on a chessboard, and the backtracking algorithm provides an efficient method of searching for all possible solutions. The N queen problem has real-world applications in computer vision, where it can be used to solve problems like object recognition and tracking.  As a result, knowing how to solve the N queen problem using backtracking is a valuable skill for any programmer.<\/p>\n<h2>FAQs(Frequently Asked Questions) on N Queen Problem<\/h2>\n<p>Here are some frequently asked questions (FAQs) and their answers on the N Queen problem:<\/p>\n<p><strong>Q1. What is the goal of the N Queen problem?<\/strong><br \/>\n<strong>Ans:<\/strong> The goal of the N Queen problem is to find a configuration of the N queens on an NxN chessboard such that no two queens are attacking each other.<\/p>\n<p><strong>Q2. What is a valid solution to the N Queen problem?<\/strong><br \/>\n<strong>Ans:<\/strong> A valid solution to the N Queen problem is a configuration of the N queens on an NxN chessboard such that no two queens are in the same row, column, or diagonal.<\/p>\n<p><strong>Q3. What is the brute force approach to solving the N Queen problem?<\/strong><br \/>\n<strong>Ans:<\/strong> The brute force approach to solving the N Queen problem involves trying all possible combinations of placing the N queens on the chessboard and checking if each combination satisfies the constraints (i.e., no two queens are in the same row, column, or diagonal).<\/p>\n<p><strong>Q4. What is the backtracking approach to solving the N Queen problem?<\/strong><br \/>\n<strong>Ans:<\/strong> The backtracking approach to solving the N Queen problem is a more efficient solution compared to the brute force approach. In this approach, we start by placing the first queen in the first row, then move to the next row and try to place the next queen, and so on. If we reach a point where it is not possible to place a queen, we backtrack and try a different position for the previous queen. We continue this process until we find a valid solution or all possibilities have been exhausted.<\/p>\n<p><strong>Q5. How can I solve the n-Queen problem?<\/strong><br \/>\n<strong>Ans:<\/strong> There are several algorithms to solve the n-Queen problem, such as backtracking, genetic algorithms, and simulated annealing. The most common algorithm is backtracking, which involves trying to place queens on the board row by row, backtracking when a conflict is found, and continuing until a solution is found.<\/p>\n<p><strong>Q6. Can the n-Queen problem be solved for all values of n?<\/strong><br \/>\n<strong>Ans:<\/strong> The n-Queen problem can be solved for all values of n, but the computational complexity of finding a solution increases rapidly as n increases. For large values of n, it may not be practical to find a solution using a brute-force algorithm.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The backtracking algorithm is used to solve the N queen problem, in which the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found. At each step, the algorithm checks to see if the newly placed queen conflicts with any previously placed queens, and if so, it [&hellip;]<\/p>\n","protected":false},"author":64,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[172],"tags":[],"class_list":["post-13265","post","type-post","status-publish","format-standard","hentry","category-backtracking"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How do you Solve the N Queen Problem?<\/title>\n<meta name=\"description\" content=\"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How do you Solve the N Queen Problem?\" \/>\n<meta property=\"og:description\" content=\"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-20T08:13:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-07-20T06:55:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\" \/>\n<meta name=\"author\" content=\"Neeraj\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Neeraj\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\"},\"author\":{\"name\":\"Neeraj\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/733e021a73de3de59e28090347670998\"},\"headline\":\"How do you Solve the N Queen Problem?\",\"datePublished\":\"2023-02-20T08:13:59+00:00\",\"dateModified\":\"2023-07-20T06:55:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\"},\"wordCount\":1634,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\",\"articleSection\":[\"Backtracking\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\",\"name\":\"How do you Solve the N Queen Problem?\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\",\"datePublished\":\"2023-02-20T08:13:59+00:00\",\"dateModified\":\"2023-07-20T06:55:36+00:00\",\"description\":\"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Backtracking\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/backtracking\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"How do you Solve the N Queen Problem?\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/733e021a73de3de59e28090347670998\",\"name\":\"Neeraj\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/aad77ffe101d901c52dba56eac1e19c1b4b6a81dfaad55c1a1350bbd36c6edba?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/aad77ffe101d901c52dba56eac1e19c1b4b6a81dfaad55c1a1350bbd36c6edba?s=96&d=mm&r=g\",\"caption\":\"Neeraj\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/neeraj\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How do you Solve the N Queen Problem?","description":"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/","og_locale":"en_US","og_type":"article","og_title":"How do you Solve the N Queen Problem?","og_description":"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.","og_url":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2023-02-20T08:13:59+00:00","article_modified_time":"2023-07-20T06:55:36+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg","type":"","width":"","height":""}],"author":"Neeraj","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Neeraj","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/"},"author":{"name":"Neeraj","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/733e021a73de3de59e28090347670998"},"headline":"How do you Solve the N Queen Problem?","datePublished":"2023-02-20T08:13:59+00:00","dateModified":"2023-07-20T06:55:36+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/"},"wordCount":1634,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg","articleSection":["Backtracking"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/","url":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/","name":"How do you Solve the N Queen Problem?","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg","datePublished":"2023-02-20T08:13:59+00:00","dateModified":"2023-07-20T06:55:36+00:00","description":"The N Queen problem is a classic problem in computer science that involves placing N chess queens on an NxN chessboard such that no two queens threaten each other.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1676638092592-How%20do%20you%20Solve%20the%20N%20Queen%20Problem.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/how-do-you-solve-the-n-queen-problem\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Backtracking","item":"https:\/\/prepbytes.com\/blog\/category\/backtracking\/"},{"@type":"ListItem","position":3,"name":"How do you Solve the N Queen Problem?"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/733e021a73de3de59e28090347670998","name":"Neeraj","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/aad77ffe101d901c52dba56eac1e19c1b4b6a81dfaad55c1a1350bbd36c6edba?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/aad77ffe101d901c52dba56eac1e19c1b4b6a81dfaad55c1a1350bbd36c6edba?s=96&d=mm&r=g","caption":"Neeraj"},"url":"https:\/\/prepbytes.com\/blog\/author\/neeraj\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/13265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/64"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=13265"}],"version-history":[{"count":5,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/13265\/revisions"}],"predecessor-version":[{"id":17287,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/13265\/revisions\/17287"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=13265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=13265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=13265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}