PROGRAM 12. Design and implement C/C++ Program for N Queen's problem using Backtracking.
#include <stdio.h>
#include <math.h>
#include <conio.h>
int x[30]; // Array to store the positions of the queens
int count = 0; // To count the number of solutions
// Function to check if a queen can be placed at the current position
int place(int k)
{
int i;
for (i = 1; i <= k-1; i++)
{
if ((x[i] == x[k]) || (abs(i-k) == abs(x[i] - x[k])))
{
return 0;
}
}
return 1;
}
// Recursive function to solve the N-Queens problem
void queens(int n)
{
int k = 1;
x[k] = 0;
while (k != 0)
{
do
{
x[k]++;
} while ((x[k] <= n) && (!place(k)));
if (x[k] <= n)
{
if (k == n)
print_solution(n);
else
{
k++;
x[k] = 0;
}
}
else
k--;
}
}
// Function to print the current board configuration
int print_solution(int n)
{
int i, j;
count++;
printf("\n Solution # %d\n", count);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (x[i] == j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}
// Main function
void main( )
{
int n;
printf("\n Enter the number of queens\n");
scanf("%d", &n);
queens(n);
printf("\n Total Solutions = %d", count);
getch();
}