0% found this document useful (0 votes)
7 views9 pages

Queens

H

Uploaded by

tahseensyed685
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Queens

H

Uploaded by

tahseensyed685
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

SOURCE CODE:

#include <iostream>
using namespace std;
int N;
int solutionsCount = 0;
int ***solutions;
void printSolution(int **board)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << (board[i][j] ? "Q " : ". ");
}
cout << endl;
}
cout << endl;
}
bool isSafe(int **board, int row, int col)
{
for (int i = 0; i < col; i++)
if (board[row][i])
return false;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (int i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}
void solveNQueensUtil(int **board, int col)
{
if (col >= N)
{
solutions[solutionsCount] = new int*[N];
for (int i = 0; i < N; i++)
{
solutions[solutionsCount][i] = new int[N];
for (int j = 0; j < N; j++)
{
solutions[solutionsCount][i][j] = board[i][j];
}
}
solutionsCount++;
return;
}
for (int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i][col] = 1;
solveNQueensUtil(board, col + 1);
board[i][col] = 0;
}
}
}
void solveNQueens()
{
cout<<"\tN-QUEENS PROBLEM"<<endl;
cout << "\nEnter the Size of the N-Queens problem: ";
cin >> N;
if (N == 2 || N == 3)
{
cout << "\nProblem cannot be solved for the size \"" << N << "\"\n";
return;
}
int **board = new int*[N];
for (int i = 0; i < N; i++)
{
board[i] = new int[N];
for (int j = 0; j < N; j++)
{
board[i][j] = 0;
}
}
solutions = new int**[1000000];
solveNQueensUtil(board, 0);
cout << "\n Solutions Found: " << solutionsCount << endl << endl;
for (int k = 0; k < solutionsCount; k++)
{
cout << "Solution " << k + 1 << ":\n";
printSolution(solutions[k]);
}
for (int i = 0; i < N; i++)
{
delete[] board[i];
}
delete[] board;
for (int k = 0; k < solutionsCount; k++)
{
for (int i = 0; i < N; i++)
{
delete[] solutions[k][i];
}
delete[] solutions[k];
}
delete[] solutions;
}

int main()
{
solveNQueens();
return 0;
}
INPUT AND OUTPUT:

You might also like