C++ Program for N Queens Problem with Output and Explanation
n x n board by checking rows, columns, and diagonals, as shown in this code snippet: bool solveNQueens(int n) { /* backtracking logic */ }.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <vector> using namespace std; bool isSafe(const vector<int>& queens, int row, int col) { for (int i = 0; i < row; ++i) { if (queens[i] == col || abs(queens[i] - col) == row - i) return false; } return true; } void printBoard(const vector<int>& queens) { int n = queens.size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << (queens[i] == j ? "Q " : ". "); } cout << "\n"; } cout << "\n"; } bool solveNQueensUtil(vector<int>& queens, int row) { int n = queens.size(); if (row == n) { printBoard(queens); return true; } bool found = false; for (int col = 0; col < n; ++col) { if (isSafe(queens, row, col)) { queens[row] = col; found = solveNQueensUtil(queens, row + 1) || found; } } return found; } int main() { int n; cout << "Enter number of queens: "; cin >> n; vector<int> queens(n, -1); if (!solveNQueensUtil(queens, 0)) { cout << "No solutions exist for n=" << n << "\n"; } return 0; }
Dry Run
Let's trace the program for n=4 through the code.
Start with row 0
Try placing queen in columns 0 to 3. Place at column 1 (safe).
Move to row 1
Try columns 0 to 3. Column 3 is safe, place queen there.
Move to row 2
Try columns 0 to 3. Column 0 is safe, place queen there.
Move to row 3
Try columns 0 to 3. Column 2 is safe, place queen there.
All queens placed
Print the board as one solution.
| Row | Queen Column |
|---|---|
| 0 | 1 |
| 1 | 3 |
| 2 | 0 |
| 3 | 2 |
Why This Works
Step 1: Check safety with isSafe
The isSafe function ensures no two queens share the same column or diagonal by comparing positions of previously placed queens.
Step 2: Backtracking tries all options
If a queen cannot be placed in any column of a row, the algorithm backtracks to the previous row to try a different column.
Step 3: Print all solutions
When all queens are placed safely, the board is printed showing one valid solution.
Alternative Approaches
#include <iostream> using namespace std; int count = 0; void solve(int n, int row, int cols, int diags1, int diags2) { if (row == n) { count++; return; } int available = ((1 << n) - 1) & ~(cols | diags1 | diags2); while (available) { int pos = available & -available; available -= pos; solve(n, row + 1, cols | pos, (diags1 | pos) << 1, (diags2 | pos) >> 1); } } int main() { int n; cout << "Enter number of queens: "; cin >> n; solve(n, 0, 0, 0, 0); cout << "Total solutions: " << count << "\n"; return 0; }
#include <iostream> #include <vector> using namespace std; int main() { int n; cout << "Enter number of queens: "; cin >> n; vector<int> queens(n, -1); int row = 0, col = 0, solutions = 0; while (row >= 0) { while (col < n) { bool safe = true; for (int i = 0; i < row; ++i) { if (queens[i] == col || abs(queens[i] - col) == row - i) { safe = false; break; } } if (safe) { queens[row] = col; col = 0; break; } else { ++col; } } if (queens[row] == -1) { --row; if (row >= 0) col = queens[row] + 1; } else if (row == n - 1) { ++solutions; queens[row] = -1; col = n; } else { ++row; } } cout << "Total solutions: " << solutions << "\n"; return 0; }
Complexity: O(n!) time, O(n) space
Time Complexity
The algorithm tries to place queens in each row and column, pruning invalid positions early, but worst case explores factorial possibilities.
Space Complexity
Uses an array of size n to store queen positions, plus recursion stack up to depth n.
Which Approach is Fastest?
Bitmask optimization is fastest for counting solutions, while backtracking with arrays is clearer and prints boards.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Backtracking with arrays | O(n!) | O(n) | Printing all solutions, clarity |
| Bitmask Optimization | O(n!) but faster in practice | O(n) | Counting solutions efficiently |
| Iterative Backtracking | O(n!) | O(n) | Avoiding recursion overhead |