(* Helper function to check if a queen can be placed at (row, col) *)
isSafe[board_, row_, col_] :=
And @@ (And[# != row, # + board[[#]] != row + col, # - board[[#]] != row - col] & /@ Range[col - 1]);
(* Recursive function to solve the 9-queens problem *)
solveQueens[board_, col_] :=
If[col > 9, (* If all queens are placed, return the solution *)
Print[board];,
(* Else, try placing the queen in each row of the current column *)
Do[
If[isSafe[board, row, col],
solveQueens[ReplacePart[board, col -> row], col + 1]; (* Recur for the next column *)
],
{row, 1, 9}
]
];
A graph of Queens on the Board of Financial Steps, leading to a test for checkmate in every direction.
Code
#include <stdio.h>
#define N 9 // Board size for the 9-queens problem
// Function to check if a queen can be placed at board[row][col]
int isSafe(int board[N], int row, int col) {
int i;
for(i = 0; i < col; i++) {
if(board[i] == row ||
board[i] - i == row - col ||
board[i] + i == row + col)
return 0; // Not safe
}
return 1; // Safe position
}
// Recursive function to solve the 9-queens problem
void solveQueens(int board[N], int col) {
if(col >= N) { // If all queens are placed, print the solution
printf("\nSolution: ");
int i;
for(i = 0; i < N; i++)
printf("%d ", board[i] + 1); // Convert 0-based to 1-based
printf("\n");
return;
}
// Try placing a queen in each row of the current column
int row;
for(row = 0; row < N; row++) {
if(isSafe(board, row, col)) {
board[col] = row; // Place queen
solveQueens(board, col + 1); // Recur for the next column
board[col] = 0; // Backtrack
}
}
}
// Main function to initialize the board and start solving
void main() {
int board[N] = {0}; // Initialize board with all zeroes
solveQueens(board, 0); // Start recursion from column 0
}
And another version :
Code
#include <stdio.h>
#define N 9 // Board size for the 9-queens problem
// Function to check if a queen can be placed at board[row][col]
int isSafe(int board[N], int row, int col) {
int i;
for (i = 0; i < col; i++) {
if (board[i] == row ||
board[i] - i == row - col ||
board[i] + i == row + col)
return 0; // Not safe
}
return 1; // Safe position
}
// Function in `f(x) = f(x - 1)` form
int solveQueens(int board[N], int col) {
if (col == 0) return 1; // Base case: when col reaches 0, return success
int prev = solveQueens(board, col - 1); // Recursive call f(x) = f(x - 1)
if (prev == 0) return 0; // If previous step failed, return failure
int row;
for (row = 0; row < N; row++) {
if (isSafe(board, row, col - 1)) { // Check previous column
board[col - 1] = row;
return 1; // Solution found
}
}
return 0; // No solution found, return failure
}
// Main function to initialize the board and start solving
void main() {
int board[N] = {0}; // Initialize board with all zeroes
solveQueens(board, N); // Start recursion from column N (reverse order)
}