Ai
1 Star 0 Fork 0

lain/OOP

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
EightQueens.java 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
lain 提交于 2024-11-18 14:24 +08:00 . 1118 EightQueens add
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 + " 个解.");
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lain_exe/oop.git
git@gitee.com:lain_exe/oop.git
lain_exe
oop
OOP
master

搜索帮助