正在研究N-queens问题。在正确填充堆栈时遇到一些困难。希望有人能给我指点。
现在我的输出是strange..There只有7个节点,但是我的“成功”布尔值需要8个节点才能为真。头节点是2,1,而我认为它应该是1,2,因为我会增加列。
我知道我也需要检查对角线,但我是一步一步来的。
我需要做的第一件事是如果我的conflictCheck方法。它永远不会返回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这是正在进行的代码/工作的一部分。现在,它正在运行一个永恒的循环,很可能是从while (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);
}}
发布于 2012-03-27 14:48:27
temp != null && temp.getNext()!= null -对于第8位皇后,值temp.getNext()为空,并且不打印。更改为:
while (temp != null ) {
System.out.println(temp.getRow() + ", " + temp.getColumn());
temp = temp.getNext();
}编辑
将||更改为&&:
if (temp.getRow() != temp.getNext().getRow() &&
temp.getColumn() != temp.getNext().getColumn()) {
return false;
}在代码queens.push(queens.size()+1, 1);中,您总是将1指定为第二个参数。你应该检查所有的可能性。
https://stackoverflow.com/questions/9881915
复制相似问题