用java中的堆栈解决n-Queen问题

用java中的堆栈解决n-Queen问题,java,data-structures,stack,n-queens,Java,Data Structures,Stack,N Queens,我一直在尝试使用java中的堆栈来解决n-queen问题。但是,代码无限运行,不会打印出任何解决方案。有人能帮我找出哪里出了问题吗 public static void nQueen(int n){ int currentPos = 0; Stack<Integer> stack = new Stack<>(); while(true){ if(currentPos < n){ if(posChecke

我一直在尝试使用java中的堆栈来解决n-queen问题。但是,代码无限运行,不会打印出任何解决方案。有人能帮我找出哪里出了问题吗

public static void nQueen(int n){
    int currentPos = 0;
    Stack<Integer> stack = new Stack<>();
    while(true){
        if(currentPos < n){
            if(posChecker(stack, currentPos)){ // checking if curr pos is valid
                stack.push(currentPos);
                currentPos = 0;
            }
            else if(!posChecker(stack, currentPos)){ // if curr pos is invalid then doing following 
                if(stack.isEmpty())
                    break;
                else{
                    currentPos = stack.pop();
                    currentPos += 1;
                }
            }
            else if(stack.getSize() == n){ //to print out the queens
                for(int j=0; j<n; j++){
                    for(int k=0; k<n; k++){
                        if(k == stack.peek()){
                            System.out.print("Q ");
                            currentPos = stack.pop()+1;
                        }
                        else System.out.print("* ");
                    }
                }
            }
        }
    }
}

public static boolean posChecker(Stack<Integer> s, int i){
    if(!s.isEmpty()){
        if(s.peek() == i) return false;
        else if(s.peek() == i-1) return false;
        else if(s.peek() == i+1) return false;
    }
    return true;
}
publicstaticvoidnquien(intn){
int currentPos=0;
堆栈=新堆栈();
while(true){
如果(当前位置对于(intj=0;jinif-else构造,只执行一个分支。
if-posChecker(stack,currentPos)重新运行falseelse执行if(posChecker(stack,currentPos)语句的分支。
在该分支中,您有另一个if-else构造:
如果(!posChecker(stack,currentPos)){}其他…
如果(stack.getSize()==n)else分支中


否则如果(stack.getSize()==n){//打印皇后你从什么开始?我从4开始,它无限运行@akuzminykhi不太明白这一点。对于打印皇后,它只是基于堆栈进行打印。它不调用posChecker方法打印皇后