【发布时间】:2015-07-14 06:48:15
【问题描述】:
我找到了一个能够在 Eclipse 中编译和运行的 8-Queen 解决方案。我相信这个解决方案遵循回溯方法,工作的核心是在solution 和unsafe 函数中完成的,但是我很难理解其中的代码路径。有人可以帮我理解这段代码在做什么。
我的来源 - http://rosettacode.org/wiki/N-queens_problem#Java 我根据其他来源上发布的 92 个解决方案验证了输出。看起来挺好的。所以我知道代码有效。
我已尝试对其进行格式化并添加一些基本注释以清除问题 -
private static int[] b = new int[8];
private static int s = 0;
public static void main(String[] args) {
// solution from - http://rosettacode.org/wiki/N-queens_problem#Java
new QueenN();
}
public QueenN() {
solution();
}
public void solution() {
int y = 0;
b[0] = -1;
while (y >= 0) {
do {
b[y]++;
} while ((b[y] < 8) && unsafe(y));
if (b[y] < 8) {
if (y < 7) {
b[++y] = -1;
} else {
putboard();
}
} else {
y--;
}
}
}
// check if queen placement clashes with other queens
public static boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x || t == x - i || t == x + i) {
return true;
}
}
return false;
}
// printing solution
public static void putboard() {
System.out.println("\n\nSolution " + (++s));
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
if (b[y] == x)
System.out.print("|Q");
else
System.out.print("|_");
}
System.out.println("|");
}
}
结束。
【问题讨论】:
标签: java backtracking n-queens