Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

N-Queens Problem Using Stacks Help

807589Apr 17 2008 — edited Jul 14 2008
I'm trying to solve the N-Queens problem using Stacks. Quite frankly, I'm completely lost.

Here's the pseudocode from the book:
"Push information onto the stack indicating the first choice is a queen in row 1, column 1.

success = false;

while(!success && !s.isEmpty())
{
Check whether the most recent choice (on top of the stack) is in the same row, same column, or same diagonal as any other choices (below the top). If so, we say there is a conflict: otherwise, there is no conflict.

if (there is a conflict)
-Pop items off the stack until the stack becomes empty or the top of the stack is a choice that is not in column n. If the stack is now not empty, then increase the column number of the top choice by 1.
else if (no conflict and the stack size is n)
-Set success to true because we have found a solution to the n-queens problem.
else
-Push information onto the stack indicating tat the next choice is to place a queen at row number s.size()+1 and column number 1.
}

And here is my excuse for code so far. I have no idea how to check the diagonals, or how to even really make this work
{code}import java.util.Stack;

public class NQueens {

int row, column, n;

public NQueens(int n) {
row = 0;
column = 0;
n = n;
}

public Stack Solve(){
boolean success, conflict;

Stack<NQueens> Qs = new Stack<NQueens>();
if (Qs.size() == 0)
Qs.push(new NQueens(1));
success = false;

while (!success && !Qs.isEmpty())
{
if (Qs.peek().row == row)
conflict = true;
if (Qs.peek().column == column)
conflict = true;
if (conflict = true)
{
Qs.pop();
Qs.peek().column += 1;
}
else
if (!conflict && Qs.size() == n)
success = true;
else
Qs.push(new NQueens(Qs.size()+1));
}

return Qs;
}

}
{code}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 11 2008
Added on Apr 17 2008
6 comments
1,162 views