The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other
#include<iostream>
#include<math.h>
using namespace std;
int x[200];
static int c = 0;
bool place(int k, int i) {
int j;
for (j = 1; j < k; j++) {
if ((x[j] == i) || (abs(x[j]-i) == abs(j-k))) {
return false;
}
}
return true;
}
void print(int n) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (x[i] == j) {
cout << "Q ";
} else {
cout << "* ";
}
}
cout << endl;
}
c++;
}
void NQueens(int k, int n) {
int i;
for (i = 1; i <= n; i++) {
if (place(k, i)) {
x[k] = i;
if (k == n) {
print(n);
cout << endl;
exit(0);
} else {
NQueens(k + 1, n);
}
}
}
}
main() {
int i, n, j;
cout << "Enter total Number of Queens" << endl;
cin >> n;
cout << endl;
NQueens(1, n);
}
Enter total Number of Queens
4
* Q * *
* * * Q
Q * * *
* * Q *
Enter total Number of Queens
8
Q * * * * * * *
* * * * Q * * *
* * * * * * * Q
* * * * * Q * *
* * Q * * * * *
* * * * * * Q *
* Q * * * * * *
* * * Q * * * *
Enter total Number of Queens
16
Q * * * * * * * * * * * * * * *
* * Q * * * * * * * * * * * * *
* * * * Q * * * * * * * * * * *
* Q * * * * * * * * * * * * * *
* * * * * * * * * * * * Q * * *
* * * * * * * * Q * * * * * * *
* * * * * * * * * * * * * Q * *
* * * * * * * * * * * Q * * * *
* * * * * * * * * * * * * * Q *
* * * * * Q * * * * * * * * * *
* * * * * * * * * * * * * * * Q
* * * * * * Q * * * * * * * * *
* * * Q * * * * * * * * * * * *
* * * * * * * * * * Q * * * * *
* * * * * * * Q * * * * * * * *
* * * * * * * * * Q * * * * * *