SlideShare a Scribd company logo
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

More Related Content

What's hot

Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
V.V.Vanniaperumal College for Women
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Backtracking
BacktrackingBacktracking
Backtracking
Dr. Jaydeep Patil
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
Animesh Chaturvedi
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Yıldırım Tam
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
hodcsencet
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
varun arora
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
Arafat Hossan
 
Traveling salesman problem
Traveling salesman problemTraveling salesman problem
Traveling salesman problem
Jayesh Chauhan
 
data structures- back tracking
data structures- back trackingdata structures- back tracking
data structures- back tracking
Abinaya B
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
Bhavin Darji
 
Travelling salesman dynamic programming
Travelling salesman dynamic programmingTravelling salesman dynamic programming
Travelling salesman dynamic programming
maharajdey
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
8 queen problem
8 queen problem8 queen problem
8 queen problem
NagajothiN1
 
An overview of gradient descent optimization algorithms
An overview of gradient descent optimization algorithms An overview of gradient descent optimization algorithms
An overview of gradient descent optimization algorithms
Hakky St
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
vikas dhakane
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
Nv Thejaswini
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtrackingmandlapure
 
Gradient descent method
Gradient descent methodGradient descent method
Gradient descent method
Sanghyuk Chun
 

What's hot (20)

Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Np complete
Np completeNp complete
Np complete
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
 
Traveling salesman problem
Traveling salesman problemTraveling salesman problem
Traveling salesman problem
 
data structures- back tracking
data structures- back trackingdata structures- back tracking
data structures- back tracking
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
 
Travelling salesman dynamic programming
Travelling salesman dynamic programmingTravelling salesman dynamic programming
Travelling salesman dynamic programming
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
8 queen problem
8 queen problem8 queen problem
8 queen problem
 
An overview of gradient descent optimization algorithms
An overview of gradient descent optimization algorithms An overview of gradient descent optimization algorithms
An overview of gradient descent optimization algorithms
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Gradient descent method
Gradient descent methodGradient descent method
Gradient descent method
 

Similar to N Queens problem

Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
dakccse
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
BinayakMukherjee4
 
Divide and Conquer / Greedy Techniques
Divide and Conquer / Greedy TechniquesDivide and Conquer / Greedy Techniques
Divide and Conquer / Greedy Techniques
Nirmalavenkatachalam
 
Optimization problems
Optimization problemsOptimization problems
Optimization problems
Ruchika Sinha
 
Computer Science Exam Help
Computer Science Exam Help Computer Science Exam Help
Computer Science Exam Help
Programming Exam Help
 
Backtracking
BacktrackingBacktracking
Backtracking
Pranay Meshram
 
Knapsack problem using fixed tuple
Knapsack problem using fixed tupleKnapsack problem using fixed tuple
Knapsack problem using fixed tuple
Mohanlal Sukhadia University (MLSU)
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
B.T.L.I.T
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
MaryJacob24
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdf
Shiwani Gupta
 
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdfCS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
OpenWorld6
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
MaryJacob24
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
MaryJacob24
 
A Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment ProblemA Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment Problem
Jim Webb
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingzukun
 
Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programming
Amisha Narsingani
 
DAA-Module-5.pptx
DAA-Module-5.pptxDAA-Module-5.pptx
DAA-Module-5.pptx
smithashetty24
 
Comparative study of different algorithms
Comparative study of different algorithmsComparative study of different algorithms
Comparative study of different algorithms
ijfcstjournal
 

Similar to N Queens problem (20)

Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
 
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.pptParallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
Parallel_Algorithms_In_Combinatorial_Optimization_Problems.ppt
 
Divide and Conquer / Greedy Techniques
Divide and Conquer / Greedy TechniquesDivide and Conquer / Greedy Techniques
Divide and Conquer / Greedy Techniques
 
Optimization problems
Optimization problemsOptimization problems
Optimization problems
 
Computer Science Exam Help
Computer Science Exam Help Computer Science Exam Help
Computer Science Exam Help
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Knapsack problem using fixed tuple
Knapsack problem using fixed tupleKnapsack problem using fixed tuple
Knapsack problem using fixed tuple
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
 
Unit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptxUnit 3- Greedy Method.pptx
Unit 3- Greedy Method.pptx
 
Analysis of Algorithm
Analysis of AlgorithmAnalysis of Algorithm
Analysis of Algorithm
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdf
 
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdfCS345-Algorithms-II-Lecture-1-CS345-2016.pdf
CS345-Algorithms-II-Lecture-1-CS345-2016.pdf
 
Unit 3 greedy method
Unit 3  greedy methodUnit 3  greedy method
Unit 3 greedy method
 
Unit 3 - Greedy Method
Unit 3  - Greedy MethodUnit 3  - Greedy Method
Unit 3 - Greedy Method
 
A Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment ProblemA Comparative Analysis Of Assignment Problem
A Comparative Analysis Of Assignment Problem
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
 
A0280115(1)
A0280115(1)A0280115(1)
A0280115(1)
 
Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programming
 
DAA-Module-5.pptx
DAA-Module-5.pptxDAA-Module-5.pptx
DAA-Module-5.pptx
 
Comparative study of different algorithms
Comparative study of different algorithmsComparative study of different algorithms
Comparative study of different algorithms
 

More from Arkadeep Dey

Java Swing
Java SwingJava Swing
Java Swing
Arkadeep Dey
 
BLACK HOLE-THE OTHER DIMENSION
BLACK HOLE-THE OTHER DIMENSIONBLACK HOLE-THE OTHER DIMENSION
BLACK HOLE-THE OTHER DIMENSION
Arkadeep Dey
 
Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.
Arkadeep Dey
 
Bhopal Gas Tragedy
Bhopal Gas TragedyBhopal Gas Tragedy
Bhopal Gas Tragedy
Arkadeep Dey
 
Data Structure in C Programming Language
Data Structure in C Programming LanguageData Structure in C Programming Language
Data Structure in C Programming Language
Arkadeep Dey
 
Hazardous-Waste Management
Hazardous-Waste Management Hazardous-Waste Management
Hazardous-Waste Management
Arkadeep Dey
 

More from Arkadeep Dey (6)

Java Swing
Java SwingJava Swing
Java Swing
 
BLACK HOLE-THE OTHER DIMENSION
BLACK HOLE-THE OTHER DIMENSIONBLACK HOLE-THE OTHER DIMENSION
BLACK HOLE-THE OTHER DIMENSION
 
Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.
 
Bhopal Gas Tragedy
Bhopal Gas TragedyBhopal Gas Tragedy
Bhopal Gas Tragedy
 
Data Structure in C Programming Language
Data Structure in C Programming LanguageData Structure in C Programming Language
Data Structure in C Programming Language
 
Hazardous-Waste Management
Hazardous-Waste Management Hazardous-Waste Management
Hazardous-Waste Management
 

Recently uploaded

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 

Recently uploaded (20)

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 

N Queens problem

  • 1. 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
  • 2. 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)
  • 3. 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
  • 4. 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
  • 5. 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.
  • 6. 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
  • 7. 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.
  • 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 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
  • 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 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.
  • 12. 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; }
  • 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 /*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;}
  • 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