Question

I'm working on the n-queens problem and am testing what I have so far to see if my logic is correct. My loop stops stops outputting and goes into an infinite loop after adjusting the 2nd queen piece so that there is no conflict.

I didn't think I'd get an infinite loop with my logic, which is basically: Push (1,1)

Check for conflict

If conflict, adjust the top queen, if it can't be adjusted, pop off, adjust the new top

If no conflict and the size < 8, push (size+1, 1) -which would obviously be a conflict

Check for conflict etc

    public static boolean conflictCheck() {
    QueenNode temp = head;
    //walk through stack and check for conflicts

    while(temp!=null) {
        //if there is no next node, there is no conflict with it
        if (temp.getNext() == null){
            System.out.println("No next node");
            if (queens.size() < 8 ) {
                System.out.println("No problems");
                return false;
            }
        }
        else if (temp.getRow() ==temp.getNext().getRow() || temp.getColumn() == temp.getNext().getColumn() ||
                diagonal(temp, temp.getNext())){
            System.out.println("There's a conflict");
            return true;
        }
    }
    return false;
}

public static void playChess() {
    System.out.println("Playing chess");
    if (conflictCheck()) {
        if (head.getColumn() == 8) {
            queens.pop();
        }
        if (!queens.isEmpty()) {
            System.out.println("Adjusting head");
            head.setColumn(head.getColumn()+1);
            System.out.println("Head is now " + head.getRow() + ", " + head.getColumn());
            playChess();

        }
    }
    else if (!conflictCheck() && queens.size() < 8) {
        System.out.println("Stack isn't full yet");
        queens.push(queens.size()+1,1);
        playChess();
        }
    else {
        success= true;
        System.out.println("Success");
        queens.viewPieces();
        return;
    }
}

public static void main(String[] args) {
    queens.push(1, 1);
    queens.viewPieces();
    success = false;
    playChess();
}

}

My output is:

The stack
1, 1
End of stack
Playing chess
No next node
No problems
No next node
No problems
Stack isn't full yet
Playing chess
There's a conflict
Adjusting head
Head is now 2, 2
Playing chess
problem
There's a conflict
Adjusting head
Head is now 2, 3
Playing chess
Was it helpful?

Solution

Was missing an extra else statement that determined when something wasn't a conflict

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top