代码拉取完成,页面将自动刷新
public class EightQueens {
private static final int N = 8; // 棋盘大小
private int[] queens; // 记录皇后所在的列
private int count; // 解的数量
public EightQueens() {
queens = new int[N];
count = 0;
}
/**
* 判断第n行的第c列是否可以放置皇后
*/
private boolean canPlace(int n, int c) {
for (int i = 0; i < n; i++) {
// 检查是否在同一列或同一对角线
if (queens[i] == c || Math.abs(queens[i] - c) == Math.abs(i - n)) {
return false;
}
}
return true;
}
/**
* 递归地放置皇后
*/
private void placeQueens(int n) {
if (n == N) { // 所有皇后都已放置,找到一个解
count++;
printSolution();
} else {
for (int c = 0; c < N; c++) {
if (canPlace(n, c)) {
queens[n] = c; // 放置皇后
placeQueens(n + 1); // 继续放置下一行
}
}
}
}
/**
* 打印当前的解
*/
private void printSolution() {
System.out.println("解 #" + count + ":");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (queens[i] == j) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
EightQueens eightQueens = new EightQueens();
eightQueens.placeQueens(0);
System.out.println("总共有 " + eightQueens.count + " 个解.");
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。