Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# How to use stack data structure to solve N Queens problem?

Posted on 2004-10-20
Medium Priority
2,651 Views
Hi there everyone,

Can anyone tell me how can I use the stack data structure(no recursive algorithm) to find all possible solutions for the N Queens puzzle and output all these solutions?

I have done the first part and find out the first solution for a N*N chessboard using StackReferenceBased class, and the code is:

import java.awt.*;
public class NQueens{

private StackReferenceBased stack;
private int size;
private Point[] stackMirror;
private boolean isSolutionFound;
private int stackSize;

public static void main(String args[]){

int noOfQueens = Integer.parseInt(args[0]);
System.out.println("The chessboard size is " + noOfQueens + "x" + noOfQueens);

NQueens queens = new NQueens(noOfQueens);
queens.search();
queens.output();
}

public NQueens(int size){
this.size = size;
stack = new StackReferenceBased();
stackMirror = new Point[size];
isSolutionFound = false;
}

public void search(){
while(true){
if(stackSize<size){//Push a Queen into stack while stack is not full
Point lastQueen = (Point)stack.peek();
Point newQueen = new Point(lastQueen.x+1,1);
stack.push(newQueen);
stackMirror[stackSize] = newQueen;
stackSize++;
}
else{
if(validate()==true){  // First solution found
isSolutionFound = true;
return;
}
else{  //backtracking
while(true){
if(stack.isEmpty()){ //If all Queens are popped,stack is empty,no solution found.
isSolutionFound = false;
return;
}

Point lastQueen = (Point)stack.pop();
--stackSize;
lastQueen.y +=1;
if(lastQueen.y>size){
continue;
}
stack.push(lastQueen);
stackMirror[stackSize] = lastQueen;
++stackSize;
break;
}
}
}
}
}

Point first = new Point(1,1);
stack.push(first);
stackMirror[0]=first;
stackSize=1;
}

public boolean validate(){
for(int i=0;i<size-1;i++){
for(int j=i+1;j<size;j++){
if(validate2Queens(stackMirror[i],stackMirror[j])==false){
return false;
}
}
}
return true;
}

public boolean validate2Queens(Point queen1, Point queen2){
if ((queen1.y == queen2.y)||
(queen1.x == queen2.x)||
((queen2.x-queen1.x) == (queen2.y-queen1.y))||
((queen1.x-queen2.x) == (queen2.y-queen1.y))){
return false;
}
return true;
}

public void output(){
if(isSolutionFound == true){
System.out.println("Solution found: (column, row)");
for(int i=0; i<size; i++){
System.out.println("Place a queen at position: ("
+stackMirror[i].x+", "+stackMirror[i].y+")");
}
}
else{
System.out.println("No solution found.");
}
}
}
0
Question by:menghao
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 5
• 3
• 2

LVL 86

Expert Comment

ID: 12359006
How did you manage to get so far without knowing the rest - perhaps because that much was given by your teacher?
0

Author Comment

ID: 12359230
yes, the rest was provided by our teacher. :)
0

LVL 86

Expert Comment

ID: 12359289
We're not allowed to do homework here. Only help with work you've already done
0

Author Comment

ID: 12359420
I just wanna get some hints on algorithm and how to find all solutions.
Cheers
0

LVL 4

Expert Comment

ID: 12374238
hi,

I'm not familiar with N queens puzzle, can you explain how puzzle normally solve on paper then maybe I can guide you through the algo.
0

Author Comment

ID: 12376631
The common N Queens problem is a eight queens puzzle based on chess, The task is to put eight queens on an empty 8*8 chessboard, such that no queen can take another queen( no two queens may be on the same horizontal, vertical or diagonal line). for eight queens, two solutions are :

Q*******              *******Q
******Q*              ***Q****
****Q***              Q*******
*******Q       or    **Q*****
*Q******              *****Q**
***Q****              *Q******
*****Q**              ******Q*
**Q*****              ****Q***

there are totally 92 solutions for 8 Queens puzzle.

To slolve this problem, using backtracking to the position in the previous column if there is no avaliable safe position in the current column.

For my problem is how can we output all solutions and how to improve the execution time using stack data structure.
0

LVL 4

Accepted Solution

funnyveryfunny earned 2000 total points
ID: 12391003
Hi,

I looked at your puzzle and initially I came up with the idea of using two stacks to solve but came to a dead end as this was not possible to produce all the solutions for every queen-start positions as I couldn't trace back.

But the good news is, with the similar idea, I have managed to solve it using 8 stacks and I have all 92 solutions.

Here is the idea of how to produce all the valid solutions to this puzzle:

1) First what we need are 8 stacks for each stack corresponds to a single row of a chessboard, so I named each stack like this row_1st, row_2nd .... row_8th. And a Point[8] array to store each combination. And a vector to store all combinations.

2) I then used waterfall-cycle like to produce all the possible solutions based on each queen_start. Each queen_start is store in row_1st stack, imagine row_1st looks like this:

|(1,8)|
|(1,7)|
|(1,6)|
|(1,5)|
|(1,4)|
|(1,3)|
|(1,2)|
|(1,2)|

3) the, we pop the first queen from row_1st stack, i.e position (1,8) and produce all the valid positions the 2nd_queen  can be on 2nd row and store these positions in row_2nd stack.

4) Similar to step 3) but on row_2nd stack, we store all the possible positions 3rd_queen can be on 3rd row in row_3rd.

5) Step 4) is then carried out until you reach row 8, which all the possible positions of 8th_queen is stored in row_8th.

6) After step 5) you have so far produce all the possible solutions to queen_start(1,8).

7) Next step is to store all these possible solutions, the procedure to storing all the positions is like trying to produce all the combinations to a safe (hacking - password guessing etc) but the only catch is every combination is valid because each stack only holds valid positions.

8) Back to step 1, pop out the next queen_start position and the process repeats until row_1st stack is empty.

A mechanical description is like this: Imagine you have 8 wheels connected to each other. Wheel 1 represents row_1st and wheel 2 represents row_2nd and so on to wheel 8=row_8th. Then wheel 1 is connected to wheel 2, and wheel 2 is connected to wheel 3....wheel 7 to 8. For every full rotation of wheel 2, wheel 1 moves by 1 click...imagine clock's hour/min/sec hands relationship. And for every full rotation of wheel 3, wheel 2 also moves by 1 click.....same applied to other wheels.

Try to understand the idea here and come up with psuedo-code for it.
0

LVL 4

Expert Comment

ID: 12391028
My program takes 170 ~ 160 millisecs to solve and 380 millisecs included console printing.

Here are some results for validation:

(1.0,5.0)(2.0,1.0)(3.0,4.0)(4.0,6.0)(5.0,8.0)(6.0,2.0)(7.0,7.0)(8.0,3.0)
(1.0,4.0)(2.0,8.0)(3.0,5.0)(4.0,3.0)(5.0,1.0)(6.0,7.0)(7.0,2.0)(8.0,6.0)
(1.0,4.0)(2.0,8.0)(3.0,1.0)(4.0,5.0)(5.0,7.0)(6.0,2.0)(7.0,6.0)(8.0,3.0)
(1.0,4.0)(2.0,8.0)(3.0,1.0)(4.0,3.0)(5.0,6.0)(6.0,2.0)(7.0,7.0)(8.0,5.0)
(1.0,4.0)(2.0,7.0)(3.0,5.0)(4.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(5.0,3.0)(6.0,7.0)(7.0,2.0)(8.0,4.0)
0

LVL 4

Expert Comment

ID: 12391032
forgot mine is based on 8x8 chessboard :)
0

LVL 4

Expert Comment

ID: 12392755
:)
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how â€¦
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different dâ€¦
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Downâ€¦
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
###### Suggested Courses
Course of the Month8 days, left to enroll