// C++ program to solve N Queen problem using Branch and
// Bound approach
#include <iostream>
#include <vector>
using namespace std;
int N;
// Function to print the solution
void printSolution(vector<vector<int> >& board)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print each cell of the board
cout << board[i][j] << " ";
}
// Print new line after each row
cout << endl;
}
}
// Optimized isSafe function to check if current row, left
// diagonal or right diagonal contains any queen
bool isSafe(int row, int col, vector<bool>& rows,
vector<bool>& leftDiagonals,
vector<bool>& rightDiagonals)
{
// Check if the current row, left diagonal, or right
// diagonal is already occupied by a queen
if (rows[row] || leftDiagonals[row + col]
|| rightDiagonals[col - row + N - 1]) {
// If occupied, it's not safe to place the queen
return false;
}
// If not occupied, it's safe to place the queen
return true;
}
// Recursive function to solve N-Queen Problem
bool solve(vector<vector<int> >& board, int col,
vector<bool>& rows, vector<bool>& leftDiagonals,
vector<bool>& rightDiagonals)
{
// Base Case: If all Queens are placed
if (col >= N) {
// All queens are placed successfully
return true;
}
// Consider this column and try placing queen in all
// rows one by one
for (int i = 0; i < N; i++) {
if (isSafe(i, col, rows, leftDiagonals,
rightDiagonals)) {
// Mark the row and diagonals as occupied
rows[i] = true;
leftDiagonals[i + col] = true;
rightDiagonals[col - i + N - 1] = true;
// Place the queen
board[i][col] = 1;
// Recur to place rest of the queens
if (solve(board, col + 1, rows, leftDiagonals,
rightDiagonals)) {
// If placing the queen in the next column
// leads to a solution, return true
return true;
}
// Backtracking: Unmark the row and diagonals,
// and remove the queen
rows[i] = false;
leftDiagonals[i + col] = false;
rightDiagonals[col - i + N - 1] = false;
// Remove the queen
board[i][col] = 0;
}
}
// If no place is safe in the current column, return
// false
return false;
}
int main()
{
// Taking input from the user
cout << "Enter the number of rows for the square "
"board: ";
// Read the size of the board
cin >> N;
// Board of size N*N
// Initialize the board with all cells as 0 (no queens
// placed)
vector<vector<int> > board(N, vector<int>(N, 0));
// Arrays to tell which rows and diagonals are occupied
// Initialize the row markers
vector<bool> rows(N, false);
// Initialize the left diagonal markers
vector<bool> leftDiagonals(2 * N - 1, false);
// Initialize the right diagonal markers
vector<bool> rightDiagonals(2 * N - 1, false);
// Start solving from the first column
bool ans = solve(board, 0, rows, leftDiagonals,
rightDiagonals);
if (ans) {
// If a solution is found, print the solution board
printSolution(board);
}
else {
// If no solution exists, print a message
cout << "Solution does not exist\n";
}
return 0;
}