|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | + |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// Function to check if it's safe to place a queen at board[row][col] |
| 7 | +bool isSafe(vector<string>& board, int row, int col, int N) { |
| 8 | + // Check the row on the left side |
| 9 | + for (int i = 0; i < col; ++i) { |
| 10 | + if (board[row][i] == 'Q') { |
| 11 | + return false; |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + // Check upper diagonal on the left side |
| 16 | + for (int i = row, j = col; i >= 0 && j >= 0; --i, --j) { |
| 17 | + if (board[i][j] == 'Q') { |
| 18 | + return false; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // Check lower diagonal on the left side |
| 23 | + for (int i = row, j = col; i < N && j >= 0; ++i, --j) { |
| 24 | + if (board[i][j] == 'Q') { |
| 25 | + return false; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return true; |
| 30 | +} |
| 31 | + |
| 32 | +// Recursive function to solve N-Queens problem |
| 33 | +bool solveNQueens(vector<string>& board, int col, int N) { |
| 34 | + if (col == N) { |
| 35 | + // All queens are placed successfully |
| 36 | + return true; |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < N; ++i) { |
| 40 | + if (isSafe(board, i, col, N)) { |
| 41 | + // Place queen |
| 42 | + board[i][col] = 'Q'; |
| 43 | + |
| 44 | + // Recur to place the rest of the queens |
| 45 | + if (solveNQueens(board, col + 1, N)) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + |
| 49 | + // If placing queen in board[i][col] doesn't lead to a solution, backtrack |
| 50 | + board[i][col] = '.'; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // If no queen can be placed in this column, return false |
| 55 | + return false; |
| 56 | +} |
| 57 | + |
| 58 | +// Function to solve N-Queens problem and print the solution |
| 59 | +void solveNQueens(int N) { |
| 60 | + vector<string> board(N, string(N, '.')); |
| 61 | + |
| 62 | + if (solveNQueens(board, 0, N)) { |
| 63 | + // Print the solution |
| 64 | + for (int i = 0; i < N; ++i) { |
| 65 | + cout << board[i] << endl; |
| 66 | + } |
| 67 | + } else { |
| 68 | + cout << "No solution exists." << endl; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +int main() { |
| 73 | + int N; |
| 74 | + cout << "Enter the number of queens (N): "; |
| 75 | + cin >> N; |
| 76 | + |
| 77 | + solveNQueens(N); |
| 78 | + |
| 79 | + return 0; |
| 80 | +} |
0 commit comments