研究 N 皇后问题。正确填充堆栈有些困难。希望任何人都可以给我任何指示。
现在我的输出很奇怪..只有 7 个节点,但我的“成功”布尔值需要 8 个才能实现。当我认为它应该是 1,2 时,头节点是 2,1,因为我会增加列。
我知道我也需要检查对角线,但我正在一步一步地进行。
如果我的冲突检查方法,我需要解决的第一件事。它永远不会返回 true(因为,是的,存在冲突)。如果我弄清楚了什么,我会尽快更新。
Hurray
8, 1
7, 1
6, 1
5, 1
4, 1
3, 1
2, 1
编辑:
我对代码进行了一些更改,以进行更递归的尝试。我的新输出是这样的:
The stack
1, 1
End of stack
Pushing next node
The stack
2, 1
1, 1
End of stack
Moving over one column
The stack
2, 2
1, 1
End of stack
problem
Moving over one column
The stack
2, 3
1, 1
End of stack
这是正在进行的代码/工作的一部分。现在,它正在进入一个永恒的循环,很可能是从那个时候开始的(conflictCheck)
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 ) {
return false;
}
}
else if (temp.getRow() ==temp.getNext().getRow() || temp.getColumn() == temp.getNext().getColumn() ||
diagonal(temp, temp.getNext())){
return true;
}
}
return false;
}
public static void mover(QueenNode n) {
System.out.println("Moving over one column");
n.setColumn(n.getColumn()+1);
queens.viewPieces();
}
public static void playChess(int k, int total) {
QueenNode temp= head;
while (temp != null) {
System.out.println("Pushing next node");
queens.push(k,1);
queens.viewPieces();
//success
if(k == 8){
System.out.println("Hurray");
success = true;
return;
}
//conflict between pieces, loops through entire board
while (conflictCheck()) {
if (head.getColumn() != 8) {
mover(head);
}
else {
queens.pop();
mover(head);
}
}
playChess(k+1, total);
}
}
public static void main(String[] args) {
queens.push(1, 1);
queens.viewPieces();
success = false;
playChess(2, total);
}
}