Java N queens算法错误和如何打印所有解决方案
以非递归方式和堆栈处理N queens问题,有两个相当具体的问题: 我的notSafe方法,它检查是否有皇后与另一个皇后在同一行/列和对角线中,但实际上不起作用。我无法发现逻辑错误,这可能是由于另一个方法完成,这可能不是正确的回溯 还有第二个问题:关于如何打印出所有解决方案有什么想法吗?也许给我一些提示让我开始Java N queens算法错误和如何打印所有解决方案,java,algorithm,n-queens,Java,Algorithm,N Queens,以非递归方式和堆栈处理N queens问题,有两个相当具体的问题: 我的notSafe方法,它检查是否有皇后与另一个皇后在同一行/列和对角线中,但实际上不起作用。我无法发现逻辑错误,这可能是由于另一个方法完成,这可能不是正确的回溯 还有第二个问题:关于如何打印出所有解决方案有什么想法吗?也许给我一些提示让我开始 import java.util.Stack; public class Test1 { static Stack<Integer> s = new Stack<I
import java.util.Stack;
public class Test1 {
static Stack<Integer> s = new Stack<Integer>();
static int topRow = 0;
static int currentRow = 0;
static int row = 0;
static int n = 8;
public static void main(String args[]) {
finish(n);
}
public static void finish(int n) {
placeQueen();
placeQueen();
boolean success = false;
while (success != true) {
if (notSafe() == true && s.empty() == false) {
int c = 1;
do {
if (c <= n) {
s.pop();
row--;
c++;
s.push(c);
row++;
} else if (c <= n && s.size() == 0) {
c++;
s.push(c);
row++;
} else {
c = 1;
s.pop();
}
} while (notSafe() == true);
} else if (s.size() == n && notSafe() == false) {
display();
break;
} else {
placeQueen();
}
}
}
public static boolean notSafe() {
boolean status = false;
int top = s.size()-1;
topRow = row;
int temp = row;
currentRow = temp - 1;
if (s.size() > 1) {
for (int m = top; m >= 1; m--) {
int x = (Integer) s.get(top);
int y = (Integer) s.get(m - 1);
if ((x == y) || x - y == currentRow || x + y == currentRow) {
status = true;
}
}
}
return status;
}
public static void placeQueen() {
s.push(1);
row++;
}
//======Display=======//
public static void display() {
int z = 0;
while (z != s.size()) {
int x = (Integer) s.pop();
for (int y = 1; y <= n; y++) {
if (x != (y)) {
System.out.print("-");
} else
System.out.print("q");
}
System.out.print("\n");
}
}
}这里需要指出的几个问题: 您似乎在前两列的第1行中放置了两个皇后。这将使解决方案非法,并假定n>1 您不需要继续测试已经放置的皇后区:只需检查您将用于下一列的行是否与之前的皇后区在同一行中即可更改方法以接受要测试的行。 如果您遵循这些建议,那么您可以简化为:
private boolean rowIsSafe(int testRow) {
for (int col = 0; col < stack.size(); col++) {
if (stack.get(col) == testRow)
return false;
if (Maths.abs(testRow - stack.get(col)) == stack.size() - col)
return false;
}
return true;
}
打印出所有的解决方案只是意味着你不会停止,也就是说,一旦找到一个解决方案就中断:打印它,弹出它,然后继续进行。也许我是唯一一个不熟悉N queens问题的人-你能帮我在你的问题中添加问题陈述的链接吗?@而且你没有queensIsSafe方法。你是说不安全吗?是的,我指的方法不安全。@AndyTurner将鼠标悬停在问题底部的n-queens标记上,或者。谢谢你的回答。我在想你说的话:这样我就不用一直测试我放的东西了?对角线呢?你只需要测试你正在添加的新部件。但我确实忘记了对角线!最后一个问题:当传递rowIsSafe一个int时,这是堆栈当前的值吗?如中所示,是否必须在循环中访问和修改堆栈,通过rowIsSafe方法进行检查,并在找到正确的解决方案时推送堆栈?是的,这是正确的。在将行推到堆栈上之前,请检查rowIsSafe。
IntStream.range(0, stack.size()).noneMatch(col -> stack.get(col) == testRow
|| Maths.abs(testRow - stack.get(col)) == stack.size() - col)