-1
我正在研究n-queens问题,并正在测试我迄今为止所看到的逻辑是否正确。我的循环停止停止输出,并在调整第二个皇后片后进入无限循环,以避免冲突。Java中的无限循环,堆栈和LinkedLists
我没想到我会得到一个无限循环与我的逻辑,这基本上是: 推送(1,1)
检查冲突
如果发生冲突,调整前的女王,如果它不能调整,爆开,调整新的顶级
如果没有冲突和大小< 8,推(尺寸+ 1,1)哪位显然是有冲突
检查冲突 等
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();
}
}
我的输出是:
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
调整头皇后2,3后额外else语句,它应该回到显示NO CONFLICT但是大小小于8的循环部分。当我注释掉playChess() – jackie 2012-03-27 14:06:30
时,会发生什么?缺少一个额外的用于确定wh有些事情不是冲突。 – jackie 2012-03-27 15:33:02