C++ Program to implement N-Queens Problem

In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally. A chess board has 8 rows and 8 columns. The standard 8 by 8 Queen’s problem asks how to place 8 queens on an ordinary chess board so that none of them can hit any other in one move. Consider an N by N “chess board” and ask if one can place N queens on such a board

Here is the code for it:

  1. #include<iostream>
  2. #include<vector>
  3. #include<fstream>
  4. #include<string>
  5. #include<algorithm>
  6. using namespace std;
  7. int ct=0;
  8. class queen
  9. {
  10.     int n;
  11. public:
  12.     void read()
  13.     {
  14.         cout<<“Enter board size\n”;
  15.         cin>>n;
  16.     }
  17.     bool place(int x[10],int k)
  18.     {
  19.         for(int i=1;i<k;i++)
  20.         {
  21.             if(x[i]==x[k]||i+x[i]==k+x[k]||i-x[i]==k-x[k])
  22.                 return false;
  23.         }
  24.         return true;
  25.     }
  26.     void nqueen()
  27.     {
  28.         int x[10];
  29.         int k=1;
  30.         x[k]=0;
  31.         while(k!=0)
  32.         {
  33.             x[k]++;
  34.             while((!place(x,k))&&(x[k]<=n))x[k]++;
  35.         if(x[k]<=n)
  36.         {
  37.             if(k==n)
  38.             {
  39.                 ct++;
  40.                 cout<<“Solution “<<ct<<“:\n”;
  41.                 print(x);
  42.                 cout<<endl;
  43.             }
  44.             else
  45.             {
  46.                 k++;
  47.                 x[k]=0;
  48.             }
  49.         }
  50.         else
  51.             k–;
  52.         }
  53.     }
  54.     void print(int x[10])
  55.     {
  56.         char c[10][10];
  57.         for(int i=1;i<=n;i++)
  58.         {
  59.             for(int j=1;j<=n;j++)
  60.                 c[i][j]=’X’;
  61.         }
  62.         for(int i=1;i<=n;i++)
  63.         {
  64.             c[i][x[i]]=’Q’;
  65.         }
  66.         for(int i=1;i<=n;i++)
  67.         {
  68.             for(int j=1;j<=n;j++)
  69.                 cout<<c[i][j];
  70.                 cout<<endl;
  71.         }
  72.         cout<<endl;
  73.     }
  74. };
  75. int main()
  76. {
  77.     queen A;
  78.     A.read();
  79.     A.nqueen();
  80.     return 0;
  81. }

 

Output:

Enter board size

4

Solution 1:

XQXX

XXXQ

QXXX

XXQX

 

Solution 2:

XXQX

QXXX

XXXQ

XQXX

Leave a comment