// placing eight queens on a chess board, basic version based on backtracking. #include using namespace std; void print(int board[]) { for (int r = 0; r < 8; r += 1) { for (int c = 0; c < 8; c += 1) if (board[r] == c) cout << "X"; else cout << "-"; cout << "\n"; } cout << "\n"; } bool all_ok(int board[], int r) { for (int i = 0; i < r; i += 1) if (board[i] == board[r]) return false; else if (i - board[i] == r - board[r]) return false; else if (i + board[i] == r + board[r]) return false; return true; } void put_queen(int board[], int r) { // the initial call is put_queen(b, 0); // given that the queens on rows 0 to r - 1 have no conflicts, ... // ... try to place a new queen in row r, ... // ... then continue to fill the board in the same way if (r == 8) { print(board); exit(0); } else for (int c = 0; c < 8; c += 1) { board[r] = c; if (all_ok(board, r)) put_queen(board, r + 1); } } int main() { int board[8]; put_queen(board, 0); }