一直试图使用Java的堆栈/回溯来解决n-queens问题.不是很有经验,试图看看我哪里出错了


public static void main(String[] args) { 
while(filled <= 7) {
conflictTest(conflict);
if (conflict == false) {
xPosition.push(x);
filled++;
y++;
n++;
x = 0;
}
else if (x == n){
x = xPosition.pop() + 1;
n--;
y--;
filled--;
}
else if (conflict = true) {
x++;                
}
conflict = false;
}
printSolution();
}

我的输出是一个充满 x 值零的堆栈,我不明白为什么。似乎在第一个 if 语句中,无论我在将第一个值推送到堆栈后也更改 x 值,我都会在堆栈的其余部分收到该值。我认为在代码中将其重置为零是正确的方法,因为当它循环回去时,它会看到冲突。

无论我在单独的方法中进行冲突测试如何,它似乎都可以做到这一点,因此我认为没有必要在此处发布,并且我的打印方法是正确的。

此外,开头的 while 语句目前限制为 8,所以我可以尝试先

让它正常工作更新

Stackoverflow告诉我我的代码太多了,所以我没有添加冲突方法。在这里

public static void conflictTest(boolean conflict) {
for (int i = 1; i < xPosition.size(); i++) { 
int j = xPosition.size()-i;
if (x == xPosition.get(i) || x == xPosition.get(i) + j 
|| x == xPosition.get(i) - j) { 
conflict = true;
}
}
}   

从你的代码冲突永远不会是真的;因为布尔数据类型是按值传递的。请参阅以下示例:

public class Test{
public static void makeMeTrue(boolean youThinkIamTrue)
{
//local value set to true but your original youThinkIamTrue still false 
youThinkIamTrue = true;
}
public static void main(String []args){
boolean youThinkIamTrue = false;
makeMeTrue(youThinkIamTrue);
//will print false
System.out.println(youThinkIamTrue);
}
}

要解决此问题,您应该更改函数

public static boolean conflictTest(boolean conflict) {
for (int i = 1; i < xPosition.size(); i++) { 
int j = xPosition.size()-i;
if (x == xPosition.get(i) || x == xPosition.get(i) + j 
|| x == xPosition.get(i) - j) { 
return true;
}
}
return conflict;
}   

并将您的呼叫代码更新为

conflict = conflictTest(conflict);

相关内容

最新更新