N QUEENS
#include <stdio.h>
#include <math.h>
// This array stores the column position of queens
int queenPositions[20];
int solutionCount = 0; // To count the number of solutions
// Function to print the board for one solution
void printSolution(int n) {
printf("\nSolution %d:\n\n", ++solutionCount);
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
// Print 'Q' if a queen is placed, else print '-'
if (queenPositions[row] == col) {
printf(" Q ");
} else {
printf(" - ");
}
}
printf("\n");
}
printf("\n");
}
// Function to check if a queen can be placed in the given row and column
int isSafe(int currentRow, int currentCol) {
for (int previousRow = 1; previousRow < currentRow; previousRow++) {
// Check if another queen is in the same column or diagonal
if (queenPositions[previousRow] == currentCol ||
abs(queenPositions[previousRow] - currentCol) == abs(previousRow - currentRow)) {
return 0; // Not safe
}
}
return 1; // Safe
}
// Function to solve the N-Queens problem
void solveNQueens(int currentRow, int n) {
// If all queens are placed, print the solution
if (currentRow > n) {
printSolution(n);
return;
}
// Try placing a queen in each column of the current row
for (int col = 1; col <= n; col++) {
if (isSafe(currentRow, col)) {
queenPositions[currentRow] = col; // Place the queen
solveNQueens(currentRow + 1, n); // Solve for the next row
}
}
}
int main() {
int n;
printf("Enter the number of queens: ");
scanf("%d", &n);
solveNQueens(1, n); // Start solving from the first row
return 0;
}
Comments
Post a Comment