1.问题描述:
要求在一个8×8的棋盘上放置8个皇后,使得任意两个皇后都不能在同一行、同一列或同一对角线上。
2.问题分析:
- 任意两个皇后所在位置的行号不相等,列号不相等,行差和列差的绝对值不相等。
- 每一行或每一列只存在1个皇后,从每一个格子开始逐个遍历,有满足的条件时则从下一行开始遍历。
3.回溯法的思想:
从第一行开始,尝试在每一列放置皇后,如果当前位置安全,则递归地在下一行放置皇后。如果下一行无法放置,则回溯到当前行,尝试下一个列位置。
4.代码实现(java)
重点是回溯
public class Demo {
private static final int N = 8; // 棋盘大小
private int[] queens; // 存储每行皇后所在的列位置
private int count = 0; // 解决方案计数
public Demo() {
queens = new int[N];
}
/**
* 回溯法解决八皇后问题
*/
public void solve() {
backtrack(0); // 从第0行开始
System.out.println("总共找到 " + count + " 种解决方案");
}
/**
* 回溯方法---重点
* @param row 当前处理的行
*/
private void backtrack(int row) {
if (row == N) {
// 找到一个解决方案
count++;
printSolution();
return;
}
// 尝试在当前行的每一列放置皇后
for (int col = 0; col < N; col++) {
if (isSafe(row, col)) {
queens[row] = col; // 放置皇后
backtrack(row + 1); // 递归处理下一行
// 回溯:不需要显式撤销,因为queens[row]会被覆盖
// backtrack(row + 1)没有满足的条件时,循环中col继续自增,也就是继续查找row中下一个满足条件的位置,若row中无满足的条件,则程序会在row-1行继续查找下一列
}
}
}
/**
* 检查在(row, col)位置放置皇后是否安全--同一列和对角线
*/
private boolean isSafe(int row, int col) {
// 检查当前列是否有冲突
for (int i = 0; i < row; i++) {
// 检查同一列 或 同一对角线(行差 == 列差)
if (queens[i] == col || Math.abs(queens[i] - col) == Math.abs(i - row)) {
return false;
}
}
return true;
}
/**
* 打印当前解决方案
*/
private void printSolution() {
System.out.println("解决方案 " + count + ":");
// 打印数字表示
System.out.print("位置: ");
for (int i = 0; i < N; i++) {
System.out.print("(" + i + "," + queens[i] + ") ");
}
System.out.println();
// 打印棋盘图示
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 int getSolutionCount() {
count = 0;
backtrackCount(0);
return count;
}
//回溯
private void backtrackCount(int row) {
if (row == N) {
count++;
return;
}
for (int col = 0; col < N; col++) {
if (isSafe(row, col)) {
queens[row] = col;
backtrackCount(row + 1);
}
}
}
public static void main(String[] args) {
HeapDemo solver = new HeapDemo();
System.out.println("八皇后问题解决方案:");
System.out.println("==================");
solver.solve();
// 如果只想获取数量
// System.out.println("解决方案总数: " + solver.getSolutionCount());
}
}

1476

被折叠的 条评论
为什么被折叠?



