#include<iostream>
#include<conio.h>
#define N 8
using namespace std;
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}
//utility function to check if placing a queen is safe
bool isSafe(int board[N][N], int row, int col)
{
//check from the left side of upper diagonal from queen's present position
for (int i = row, j = col; i >= 0 && j >= 0; --i, --j)
{
if (board[i][j] )
return false;
}
//similarly check from queens bottom diagonal from the lefts side
for (int i = row, j = col; i < N && j >= 0; ++i, --j)
{
if (board[i][j])
return false;
}
//check for queens left col
for (int i = 0; i <col ; ++i)
if (board[row][i])
return false;
return true;
}
// a utility function to solve n queens problem recursively
bool solveNQueenUtil(int board[N][N], int col)
{
//base case
if (col >= N)
return true;
//considering each row once for a column
for (int i = 0; i < N; ++i)
{
if (isSafe(board, i, col))
{
board[i][col] = 1;
if (solveNQueenUtil(board, col + 1) )
return true;
//backtrack
board[i][col] = 0;
}
}
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }
};
if (solveNQueenUtil(board, 0) == false)
{
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
// driver program to test above function
int main()
{
solveNQ();
getchar();
return 0;
}
No comments:
Post a Comment