Final answer:
To solve the 8 queens problem in C++, you can use a recursive function and a 1-dimensional array to represent the queen positions on the chessboard. The 'isSafe' function is used to check the validity of queen placements, ensuring that no two queens attack each other. The program prints all possible solutions for placing 8 queens on an 8x8 chessboard.
Step-by-step explanation:
8 Queens Problem in C++ using Backtracking
To solve the 8 queens problem in C++ using backtracking and a 1-dimensional array, you can create a recursive function that checks for valid queen placements on the chessboard. Here's an example code:
#include <iostream>
#define SIZE 8
int board[SIZE];
bool isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
int diff = abs(board[i] - col);
if (diff == 0 || diff == row - i) {
return false;
}
}
return true;
}
void solveQueens(int row) {
if (row == SIZE) {
for (int i = 0; i < SIZE; i++) {
std::cout << board[i] + 1 << " ";
}
std::cout << std::endl;
return;
}
for (int col = 0; col < SIZE; col++) {
if (isSafe(row, col)) {
board[row] = col;
solveQueens(row + 1);
}
}
}
int main() {
solveQueens(0);
return 0;
}
This code uses a 1-dimensional array 'board' to represent the positions of the queens on each row, and a recursive function 'solveQueens' to place the queens row by row. The 'isSafe' function checks if a particular position is safe from attacks by other queens. The program prints all possible solutions for placing 8 queens on an 8x8 chessboard.