我正在研究n-queens问题并且正在测试我到目前为止所看到的逻辑是否正确。我的循环停止输出,并在调整第二个皇后片后进入无限循环,这样就没有冲突。
我认为我的逻辑没有得到无限循环,基本上是: 按(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
答案 0 :(得分:1)
错过了一个额外的声明,确定什么时候不是冲突