#include #include #include using namespace std; bool valid (const vector & board, int maxcol) { for (int i = 0; i < maxcol; i++) { for (int j = i+1; j < maxcol; j++) { if (board[i] == board[j]) // rows collide --- queens under threat { return false; } if (j-i == abs(board[i]-board[j])) // diagonals collide --- queens under threat { return false; } } } return true; } bool solve_8queens (int column, vector & board) { if (column > 8) { return true; // we only call the next level if everything up to the // current level was fine --- if we call for column 9, // it means that we have our solution } for (int row = 0; row < 8; row++) { board[column] = row; if (valid(board, column)) { if (solve_8queens (column+1, board)) { return true; } } } // we completed the loop and nothing worked; backtrack // and have the previous level keep trying return false; } int main() { vector board(8); if (solve_8queens(0, board)) { for (int i = 0; i < 8; i++) { cout << board[i] << " "; } } cout << endl; }