N-Queens,使用LinkedList堆栈的Java
研究N皇后问题。在正确填充堆栈时有一些困难。希望有人能给我一些建议 现在我的输出很奇怪。只有7个节点,但我的“成功”布尔值需要8才能为真。当我认为它应该是1,2时,头部节点是2,1,因为我会增加列 我知道我也需要检查对角线,但我正在一步一步地做 我首先要解决的是我的conflictCheck方法是否正确。它永远不会变成真的,因为存在冲突。如果我发现了什么,我会很快更新N-Queens,使用LinkedList堆栈的Java,java,linked-list,stack,n-queens,Java,Linked List,Stack,N Queens,研究N皇后问题。在正确填充堆栈时有一些困难。希望有人能给我一些建议 现在我的输出很奇怪。只有7个节点,但我的“成功”布尔值需要8才能为真。当我认为它应该是1,2时,头部节点是2,1,因为我会增加列 我知道我也需要检查对角线,但我正在一步一步地做 我首先要解决的是我的conflictCheck方法是否正确。它永远不会变成真的,因为存在冲突。如果我发现了什么,我会很快更新 Hurray 8, 1 7, 1 6, 1 5, 1 4, 1 3, 1 2, 1 编辑: 我对代码做了一些更改,以进行更递归
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
这是代码/正在进行的工作的一部分。现在,它正在运行一个永恒的循环,很可能是在冲突检查时
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);
}
}温度!=null&临时获取下一步!=null-对于第8个queen,temp.getNext的值为null,并且未打印。改为:
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;
}
在CodeQueens.pushqueens.size+1,1中;始终将1指定为第二个参数。你应该检查所有的可能性。我做了一些编辑,我正试图找出如何处理冲突。如果存在冲突且顶部的列为8,则要将其弹出,并将下一个顶部的列上移1。如果列不是8,只需将顶部的列上移1,然后重新检查是否存在冲突。现在,我有一个永恒的循环:/