// This time N queens on a chess board, same basic backtracking, now show all solutions. #include using namespace std; void print(int board[], int size) { for (int r = 0; r < size; r += 1) { for (int c = 0; c < size; 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 size, 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 == size) print(board, size); else for (int c = 0; c < size; c += 1) { board[r] = c; if (all_ok(board, r)) put_queen(board, size, r + 1); } } int main(int argc, char * argv[]) { int size = 8; if (argc > 1) { char * c; size = strtol(argv[1], & c, 10); if (* c != '\0' || size < 1) { cerr << argv[1] << " is not a usable number\n"; exit(1); } } int * board = new int[size]; put_queen(board, size, 0); delete [] board; }