Assignment 6: Write a recursive program to find the solution of placing n queens on chess board so that no queen takes each other (backtracking).
Problem Statement: Write a recursive program to find the solution of placing n queens on chess board so that no queen takes each other (backtracking).
The N Queen is the problem of placing N chess queens on an
N×N chessboard so that no two queens attack each other. For example, following
is a solution for 4 Queen problem.
The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the output matrix for above 4 queen solution.
{
0, 1,
0, 0}
{
0, 0,
0, 1}
{
1, 0,
0, 0}
{ 0, 0, 1, 0}
Naive Algorithm
Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints.
while there are untried configurations
{
generate the next
configuration
if queens don't
attack in this configuration then
{
print this
configuration;
}
}
Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from the
leftmost column. When we place a queen in a column, we check for clashes with
already placed queens. In the current column, if we find a row for which there
is no clash, we mark this row and column as part of the solution. If we do not
find such a row due to clashes then we backtrack and return false.
If there is a queen ‘Q’ positioned to the left of column C in row R, then
return False;
If there is queen ‘Q’ positioned on the upper left diagonal, then
return false;
If there is queen ‘Q’ positioned on the lower left diagonal, then
return false;
return true;
}
PlaceNQueens ( chessboard, column )
a) If the chessboard size equals column number (chessboard.size() == column)
All the queens are correctly placed on the chessboard. Display the chessboard.
b) Else try placing the queen on each row of the column and check if the chessboard remains valid.
for ( row = 0; row < chessboard.size(); row++ )
Place the queen ‘Q’ at position [ row, column ] and check if the chessboard remains valid
chessboard [ row ] [ column ] = ' Q ‘
Check if ( IsBoardOk ( chessboard, row, column ) == true ) {
Try placing another queen ‘Q’ in the next column.
PlaceNQueens ( chessboard, column + 1 ) ;
}
Chessboard was not valid hence revert
chessboard [ row ] [ column ] = ' . ‘.
Time complexity of N queens algorithm : For finding a single solution where the first queen ‘Q’ has been assigned the first column and can be put on N positions, the second queen has been assigned the second column and would choose from N-1 possible positions and so on; the time complexity is O ( N ) * ( N - 1 ) * ( N - 2 ) * … 1 ). i.e The worst-case time complexity is O ( N! ). Thus, for finding all the solutions to the N Queens problem the time complexity runs in polynomial time.
Comments
Post a Comment