8 QUEENS PROBLEM
A Micro Project on Object Oriented Programming (C++)
By
Arkadeep Dey(CSE2015/30)
Apu Sarkar(CSE2015/02)
Kshitij raj(CSE2015/07)
Astha Mishra(CSE2015/11)
Ravi Prakash(CSE2015/22)
UNDER THE GUIDANCE OF
HARINANDAN TUNGA
PROJECT REPORT SUBMITTED IN PARTIAL FULFILLMENT OF THE
REQUIREMENT FOR THE DEGREE OF BACHELOR OF TECHNOLOGY IN
COMPUTER SCIENCE AND ENGINEERING
RCC INSTITUTE OF INFORMATION TECHNOLOGY
Page | 1
CERTIFICATE OF APPROVAL
The foregoing Project is hereby accepted
as a credible study of an engineering subject
carried out and presented in a manner
satisfactory to warrant its acceptance as a
prerequisite to the degree for which it has
been submitted. It is understood that by this
approval the undersigned do not necessarily
endorse or approve any statement made,
opinion expressed or conclusion drawn
therein, but approve the project only for the
purpose for which it is submitted.
FINAL EXAMINATION FOR 1 __________________
EVALUATION OF PROJECT 2 __________________
(Signature of Examiner)
Page | 2
ACKNOWLEDGEMENT
In performing our assignment, we had to take the help
and guideline of some respected persons, who deserve our
greatest gratitude. The completion of this assignment gives us
much Pleasure. We would like to show our gratitude Prof.
Harinandan Tunga, Assistant Professor, The Department of
Computer Science and Technology, RCC Institute of
Information Technology for giving us a good guideline for
assignment throughout numerous consultations. We would
also like to expand our deepest gratitude to all those who have
directly and indirectly guided us in writing this assignment. In
addition, a thank you to Mr. Bishal Ghosh, who introduced us
to the Methodology of work, and whose passion for the
“underlying structures” had lasting effect. Many people,
especially our classmates and team members itself, have made
valuable comment suggestions on this proposal which gave us
an inspiration to improve our assignment. We thank all the
people for their help directly and indirectly to complete our
assignment
Page | 3
Table of content
CONTENTS PAGE NO.
I. ABSTRACT 04
II. Introduction 05
III. Methodology 06
IV. Algorithm 07
V. Time complexity 08
VI. Flow chart 08
VII. Results & discussion 09
VIII. Conclusion 10
IX. Source code 11
X. Reference 15
Page | 4
ABSTRACT
This article details the formal specification and verification of the
n-queen problem. The main purpose of this article is to specify and verify
the abstract model of a C ++ program which computes all the possible
solutions to the n-queen problem. In this paper, a solution is proposed for
n-Queen problem based on Backtracking algorithm. Backtracking is a
standard-method to find solutions for particular kind of problems, known
as "Constraint-Satisfaction"-Problems. These Problems define a set of
Constraints to validate any trial. The most primitive way to solve them
is "Brute-Force" - that means: Simply try everything out. The n-Queen
problem become intractable for large values of `n' and thus placed in NP
(non-deterministic polynomial) class problem. The n-Queen problem is
basically a generalized form of 8-Queen problem. In n-Queen problem,
the goal is to place ‘n’ queens such that no queen can kill the other using
standard chess queen moves. The solution can very easily be extended
to the generalized form of the problem for large values of `n'. The paper
contains the detail discussion of problem background, problem
complexity and conclusion.
Page | 5
Introduction
Chess composer Max Bezzel published the eight queens
puzzle in 1848. Franz Nauck published the first solutions in
1850.Nauck also extended the puzzle to the n queens problem,
with n queens on a chessboard of n × n squares.
Since then, many mathematicians, including Carl Friedrich
Gauss, have worked on both the eight queens puzzle and its
generalized n-queens version. In 1874, S. Gunther proposed a
method using determinants to find solutions.J.W.L.
Glaisher refined Gunther's approach.
In 1972, Edsger Dijkstra used this problem to illustrate the power
of what he called structured programming. He published a highly
detailed description of a depth-first backtracking algorithm.
The classic example of the use of backtracking is the eight
queens puzzle, that asks for all arrangements of
eight chessqueens on a standard chessboard so that no queen
attacks any other. In the common backtracking approach, the
partial candidates are arrangements of k queens in the first k rows
of the board, all in different rows and columns. Any partial solution
that contains two mutually attacking queens can be abandoned.
The problem can be quite computationally expensive, as there are
4,426,165,368 (i.e., 64C8) possible arrangements of eight queens
on an 8×8 board, but only 92 solutions. It is possible to use
shortcuts that reduce computational requirements or rules of
thumb that avoids brute-force computational techniques. For
example, by applying a simple rule that constrains each queen to
a single column (or row), though still considered brute force, it is
possible to reduce the number of possibilities to 16,777,216 (that
is, 88
) possible combinations. Generating permutations further
reduces the possibilities to just 40,320 (that is, 8!), which are then
checked for diagonal attacks.
Martin Richards published a program to count solutions to the n-
queens problem using bitwise operations.[3]
. However, this
solution has already been published by Zongyan Qiu
Page | 6
Methodology
Backtracking is a general algorithm for finding all (or some)
solutions to some computational problems, notably constraint
satisfaction problems, that incrementally builds candidates to the
solutions, and abandons each partial candidate ("backtracks") as
soon as it determines that the candidate cannot possibly be
completed to a valid solution.[1][2]
The backtracking algorithm enumerates a set of partial
candidates that, in principle, could be completed in various ways
to give all the possible solutions to the given problem. The
completion is done incrementally, by a sequence of candidate
extension steps.
Conceptually, the partial candidates are represented as the nodes
of a tree structure, the potential search tree. Each partial
candidate is the parent of the candidates that differ from it by a
single extension step; the leaves of the tree are the partial
candidates that cannot be extended any further.
The backtracking algorithm traverses this search tree recursively,
from the root down, in depth-first order. At each node c, the
algorithm checks whether c can be completed to a valid solution.
If it cannot, the whole sub-tree rooted at c is skipped (pruned).
Otherwise, the algorithm (1) checks whether c itself is a valid
solution, and if so reports it to the user; and (2) recursively
enumerates all sub-trees of c. The two tests and the children of
each node are defined by user-given procedures.
Therefore, the actual search tree that is traversed by the algorithm
is only a part of the potential tree. The total cost of the algorithm
is the number of nodes of the actual tree times the cost of
obtaining and processing each node. This fact should be
considered when choosing the potential search tree and
implementing the pruning test.
Page | 7
Algorithm
Algorithm:
1. Place the queens column wise, start from the left most column
2. If all queens are placed.
1. return true and print the solution matrix.
3. Else
1. Try all the rows in the current column.
2. Check if queen can be placed here safely if yes mark the current
cell in solution matrix as 1 and try to solve the rest of the prob-
lem recursively.
3. If placing the queen in above step leads to the solution return
true.
4. If placing the queen in above step does not lead to the solution
, BACKTRACK, mark the current cell in solution matrix as 0
and return false.
4. If all the rows are tried and nothing worked, return false and
print NO SOLUTION.
Page | 8
Time complexity
From what we can tell, the recurrence is T(n) = n*T(n-1)
+ N*n, which leads to O((n+1)!). When one more recursive call
is made, at least one more isSafe() should return false. So the
number of recursive calls decreases by at least 1 each time. And
for the overhead in isSafe(), since col rows has been filled
already, there are at most min(col, N-col+1) iterations of for
(i = 0; i < col; i++). But the for loop
in solveNQUtil() runs a fixed number of N. That's
why N*n exists.
But many people argue that N-queen runs O(n!) with
recurrence T(n)= n*(T(n-1) + O(n))
Flow chart
Page | 9
Results & discussion
The eight queens puzzle has 92 distinct solutions. If solutions
that differ only by the symmetry operations of rotation and reflection
of the board are counted as one, the puzzle has 12 solutions. These
are called fundamental solutions; representatives of each are
shown…below.
A fundamental solution usually has eight variants (including its
original form) obtained by rotating 90, 180, or 270° and then
reflecting each of the four rotational variants in a mirror in a fixed
position. However, should a solution be equivalent to its own 90°
rotation (as happens to one solution with five queens on a 5×5
board), that fundamental solution will have only two variants (itself
and its reflection). Should a solution be equivalent to its own 180°
rotation (but not to its 90° rotation), it will have four variants (itself
and its reflection, its 90° rotation and the reflection of that). If n >
1, it is not possible for a solution to be equivalent to its own
reflection because that would require two queens to be facing
each other. Of the 12 fundamental solutions to the problem with
eight queens on an 8×8 board, exactly one (solution 12 below) is
Page | 10
equal to its own 180° rotation, and none is equal to its 90° rotation;
thus, the number of distinct solutions is 11×8 + 1×4 = 92 (where
the 8 is derived from four 90° rotational positions and their
reflections, and the 4 is derived from two 180° rotational positions
and their reflections).
Conclusion
Finding all solutions to the eight queens puzzle is a good
example of a simple but nontrivial problem. For this reason, it is
often used as an example problem for various programming
techniques, including nontraditional approaches such
as constraint programming, logic programming or genetic
algorithms. Most often, it is used as an example of a problem that
can be solved with a recursive algorithm, by phrasing
the n queens problem inductively in terms of adding a single
queen to any solution to the problem of placing n−1 queens on an
n-by-n chessboard.
Page | 11
Source code
#include<iostream>
#include<cmath>
#include<stdlib.h>
using namespace std;
int board[20],count=0;
void queen(int ,int);
int main(){
int n;
cout<<("Enter the queens number");
cin>>n;
queen(1,n);
return 0;
}
Page | 12
/* print solution */
void print(int N)
{
cout<<"Solution"<<++count<<":nn";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++){
if(board[i]==j)
cout<<"Qnt";
else
cout<<"0t";
} cout<<"n";
}
}
Page | 13
/*check if a queen can be placed on board[r]*/
int place(int row,int column){
int j;
int flag=1;
for(j=1;j<=row-1;j++){
if((board[j]==column) ||
(abs(board[j]-column)==abs(j-row))){
flag= 0;
}
}
return flag;}
Page | 14
/* solves the N Queen problem using Backtracking.*/
void queen(int row ,int n){
int j;
for(j=1;j<=n;j++){
if(place(row,j)==1){
board[row]=j;
if(row==n){print(n);
}else{
queen(row+1,n);
}
}
}
}
Page | 15
Reference
 Eight queens puzzle
 (https://en.wikipedia.org/wiki/Eight_quee
ns_puzzle)
 FUNDAMENTAL OF COMPUTER
ALGORITHMS
 ELLIS HOROWITZ,SARTAJ SAHANI
 OBJECT ORIENTED PROGRAMMING
USING C++
 G.K.BALUJA,G.S. BALUJA
Page | 16

N Queens problem

  • 1.
    8 QUEENS PROBLEM AMicro Project on Object Oriented Programming (C++) By Arkadeep Dey(CSE2015/30) Apu Sarkar(CSE2015/02) Kshitij raj(CSE2015/07) Astha Mishra(CSE2015/11) Ravi Prakash(CSE2015/22) UNDER THE GUIDANCE OF HARINANDAN TUNGA PROJECT REPORT SUBMITTED IN PARTIAL FULFILLMENT OF THE REQUIREMENT FOR THE DEGREE OF BACHELOR OF TECHNOLOGY IN COMPUTER SCIENCE AND ENGINEERING RCC INSTITUTE OF INFORMATION TECHNOLOGY
  • 2.
    Page | 1 CERTIFICATEOF APPROVAL The foregoing Project is hereby accepted as a credible study of an engineering subject carried out and presented in a manner satisfactory to warrant its acceptance as a prerequisite to the degree for which it has been submitted. It is understood that by this approval the undersigned do not necessarily endorse or approve any statement made, opinion expressed or conclusion drawn therein, but approve the project only for the purpose for which it is submitted. FINAL EXAMINATION FOR 1 __________________ EVALUATION OF PROJECT 2 __________________ (Signature of Examiner)
  • 3.
    Page | 2 ACKNOWLEDGEMENT Inperforming our assignment, we had to take the help and guideline of some respected persons, who deserve our greatest gratitude. The completion of this assignment gives us much Pleasure. We would like to show our gratitude Prof. Harinandan Tunga, Assistant Professor, The Department of Computer Science and Technology, RCC Institute of Information Technology for giving us a good guideline for assignment throughout numerous consultations. We would also like to expand our deepest gratitude to all those who have directly and indirectly guided us in writing this assignment. In addition, a thank you to Mr. Bishal Ghosh, who introduced us to the Methodology of work, and whose passion for the “underlying structures” had lasting effect. Many people, especially our classmates and team members itself, have made valuable comment suggestions on this proposal which gave us an inspiration to improve our assignment. We thank all the people for their help directly and indirectly to complete our assignment
  • 4.
    Page | 3 Tableof content CONTENTS PAGE NO. I. ABSTRACT 04 II. Introduction 05 III. Methodology 06 IV. Algorithm 07 V. Time complexity 08 VI. Flow chart 08 VII. Results & discussion 09 VIII. Conclusion 10 IX. Source code 11 X. Reference 15
  • 5.
    Page | 4 ABSTRACT Thisarticle details the formal specification and verification of the n-queen problem. The main purpose of this article is to specify and verify the abstract model of a C ++ program which computes all the possible solutions to the n-queen problem. In this paper, a solution is proposed for n-Queen problem based on Backtracking algorithm. Backtracking is a standard-method to find solutions for particular kind of problems, known as "Constraint-Satisfaction"-Problems. These Problems define a set of Constraints to validate any trial. The most primitive way to solve them is "Brute-Force" - that means: Simply try everything out. The n-Queen problem become intractable for large values of `n' and thus placed in NP (non-deterministic polynomial) class problem. The n-Queen problem is basically a generalized form of 8-Queen problem. In n-Queen problem, the goal is to place ‘n’ queens such that no queen can kill the other using standard chess queen moves. The solution can very easily be extended to the generalized form of the problem for large values of `n'. The paper contains the detail discussion of problem background, problem complexity and conclusion.
  • 6.
    Page | 5 Introduction Chesscomposer Max Bezzel published the eight queens puzzle in 1848. Franz Nauck published the first solutions in 1850.Nauck also extended the puzzle to the n queens problem, with n queens on a chessboard of n × n squares. Since then, many mathematicians, including Carl Friedrich Gauss, have worked on both the eight queens puzzle and its generalized n-queens version. In 1874, S. Gunther proposed a method using determinants to find solutions.J.W.L. Glaisher refined Gunther's approach. In 1972, Edsger Dijkstra used this problem to illustrate the power of what he called structured programming. He published a highly detailed description of a depth-first backtracking algorithm. The classic example of the use of backtracking is the eight queens puzzle, that asks for all arrangements of eight chessqueens on a standard chessboard so that no queen attacks any other. In the common backtracking approach, the partial candidates are arrangements of k queens in the first k rows of the board, all in different rows and columns. Any partial solution that contains two mutually attacking queens can be abandoned. The problem can be quite computationally expensive, as there are 4,426,165,368 (i.e., 64C8) possible arrangements of eight queens on an 8×8 board, but only 92 solutions. It is possible to use shortcuts that reduce computational requirements or rules of thumb that avoids brute-force computational techniques. For example, by applying a simple rule that constrains each queen to a single column (or row), though still considered brute force, it is possible to reduce the number of possibilities to 16,777,216 (that is, 88 ) possible combinations. Generating permutations further reduces the possibilities to just 40,320 (that is, 8!), which are then checked for diagonal attacks. Martin Richards published a program to count solutions to the n- queens problem using bitwise operations.[3] . However, this solution has already been published by Zongyan Qiu
  • 7.
    Page | 6 Methodology Backtrackingis a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons each partial candidate ("backtracks") as soon as it determines that the candidate cannot possibly be completed to a valid solution.[1][2] The backtracking algorithm enumerates a set of partial candidates that, in principle, could be completed in various ways to give all the possible solutions to the given problem. The completion is done incrementally, by a sequence of candidate extension steps. Conceptually, the partial candidates are represented as the nodes of a tree structure, the potential search tree. Each partial candidate is the parent of the candidates that differ from it by a single extension step; the leaves of the tree are the partial candidates that cannot be extended any further. The backtracking algorithm traverses this search tree recursively, from the root down, in depth-first order. At each node c, the algorithm checks whether c can be completed to a valid solution. If it cannot, the whole sub-tree rooted at c is skipped (pruned). Otherwise, the algorithm (1) checks whether c itself is a valid solution, and if so reports it to the user; and (2) recursively enumerates all sub-trees of c. The two tests and the children of each node are defined by user-given procedures. Therefore, the actual search tree that is traversed by the algorithm is only a part of the potential tree. The total cost of the algorithm is the number of nodes of the actual tree times the cost of obtaining and processing each node. This fact should be considered when choosing the potential search tree and implementing the pruning test.
  • 8.
    Page | 7 Algorithm Algorithm: 1.Place the queens column wise, start from the left most column 2. If all queens are placed. 1. return true and print the solution matrix. 3. Else 1. Try all the rows in the current column. 2. Check if queen can be placed here safely if yes mark the current cell in solution matrix as 1 and try to solve the rest of the prob- lem recursively. 3. If placing the queen in above step leads to the solution return true. 4. If placing the queen in above step does not lead to the solution , BACKTRACK, mark the current cell in solution matrix as 0 and return false. 4. If all the rows are tried and nothing worked, return false and print NO SOLUTION.
  • 9.
    Page | 8 Timecomplexity From what we can tell, the recurrence is T(n) = n*T(n-1) + N*n, which leads to O((n+1)!). When one more recursive call is made, at least one more isSafe() should return false. So the number of recursive calls decreases by at least 1 each time. And for the overhead in isSafe(), since col rows has been filled already, there are at most min(col, N-col+1) iterations of for (i = 0; i < col; i++). But the for loop in solveNQUtil() runs a fixed number of N. That's why N*n exists. But many people argue that N-queen runs O(n!) with recurrence T(n)= n*(T(n-1) + O(n)) Flow chart
  • 10.
    Page | 9 Results& discussion The eight queens puzzle has 92 distinct solutions. If solutions that differ only by the symmetry operations of rotation and reflection of the board are counted as one, the puzzle has 12 solutions. These are called fundamental solutions; representatives of each are shown…below. A fundamental solution usually has eight variants (including its original form) obtained by rotating 90, 180, or 270° and then reflecting each of the four rotational variants in a mirror in a fixed position. However, should a solution be equivalent to its own 90° rotation (as happens to one solution with five queens on a 5×5 board), that fundamental solution will have only two variants (itself and its reflection). Should a solution be equivalent to its own 180° rotation (but not to its 90° rotation), it will have four variants (itself and its reflection, its 90° rotation and the reflection of that). If n > 1, it is not possible for a solution to be equivalent to its own reflection because that would require two queens to be facing each other. Of the 12 fundamental solutions to the problem with eight queens on an 8×8 board, exactly one (solution 12 below) is
  • 11.
    Page | 10 equalto its own 180° rotation, and none is equal to its 90° rotation; thus, the number of distinct solutions is 11×8 + 1×4 = 92 (where the 8 is derived from four 90° rotational positions and their reflections, and the 4 is derived from two 180° rotational positions and their reflections). Conclusion Finding all solutions to the eight queens puzzle is a good example of a simple but nontrivial problem. For this reason, it is often used as an example problem for various programming techniques, including nontraditional approaches such as constraint programming, logic programming or genetic algorithms. Most often, it is used as an example of a problem that can be solved with a recursive algorithm, by phrasing the n queens problem inductively in terms of adding a single queen to any solution to the problem of placing n−1 queens on an n-by-n chessboard.
  • 12.
    Page | 11 Sourcecode #include<iostream> #include<cmath> #include<stdlib.h> using namespace std; int board[20],count=0; void queen(int ,int); int main(){ int n; cout<<("Enter the queens number"); cin>>n; queen(1,n); return 0; }
  • 13.
    Page | 12 /*print solution */ void print(int N) { cout<<"Solution"<<++count<<":nn"; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++){ if(board[i]==j) cout<<"Qnt"; else cout<<"0t"; } cout<<"n"; } }
  • 14.
    Page | 13 /*checkif a queen can be placed on board[r]*/ int place(int row,int column){ int j; int flag=1; for(j=1;j<=row-1;j++){ if((board[j]==column) || (abs(board[j]-column)==abs(j-row))){ flag= 0; } } return flag;}
  • 15.
    Page | 14 /*solves the N Queen problem using Backtracking.*/ void queen(int row ,int n){ int j; for(j=1;j<=n;j++){ if(place(row,j)==1){ board[row]=j; if(row==n){print(n); }else{ queen(row+1,n); } } } }
  • 16.
    Page | 15 Reference Eight queens puzzle  (https://en.wikipedia.org/wiki/Eight_quee ns_puzzle)  FUNDAMENTAL OF COMPUTER ALGORITHMS  ELLIS HOROWITZ,SARTAJ SAHANI  OBJECT ORIENTED PROGRAMMING USING C++  G.K.BALUJA,G.S. BALUJA
  • 17.