1、八皇后问题
-
在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
2、Java代码
package Algorithm.Recursion;
/**
* @author yhx
* @date 2020/09/28
*/
public class Queue8 {
/**
* max:共有多少个皇后
* array:每个皇后的位置,例如array[2]=4,表示第3个皇后在棋盘第3行第5列的位置上
* count:正确解法的个数
*/
int max = 8;
int[] array = new int[max];
static int count = 0;
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
queue8.check(0);
System.out.printf("一共有%d种解法",count);
}
/**
* 将皇后摆放位置输出
*/
private void print() {
count++;
for (int j : array) {
System.out.print(j + " ");
}
System.out.println();
}
/**
* 当放置第n个皇后,检测该皇后与前面的皇后位置是否冲突
*
* @param n 第n个皇后
* @return 返回皇后位置是否冲突
*/
private boolean judge(int n) {
for (int i = 0; i < n; i++) {
// 1、array[i] == array[n] 说明有皇后在同一列
// 2、Math.abs(n - i) == Math.abs(array[n] - array[i]) 说明有皇后在同一斜线
// 3、由于一维数组对皇后位置的定义,两皇后不可能处于同一行
if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
return false;
}
}
return true;
}
/**
* 回溯求解
*
* @param n 第几个皇后
*/
private void check(int n) {
// 当开始放置第9个皇后,说明前面8个皇后已经放置完毕,可以打印输出
if (n == max) {
print();
return;
}
// 依次放入皇后,并判断是否冲突
for (int i = 0; i < max; i++) {
// 从皇后本行的第一列开始放置
array[n] = i;
// 判断位置是否冲突
if (judge(n)) {
// 如果不冲突就递归放置
check(n + 1);
}
// 如果位置冲突,就将皇后沿本行后移一列
}
}
}
3、运行结果
0 4 7 5 2 6 1 3
0 5 7 2 6 3 1 4
0 6 3 5 7 1 4 2
0 6 4 7 1 3 5 2
1 3 5 7 2 0 6 4
1 4 6 0 2 7 5 3
1 4 6 3 0 7 5 2
1 5 0 6 3 7 2 4
1 5 7 2 0 3 6 4
1 6 2 5 7 4 0 3
1 6 4 7 0 3 5 2
1 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