/*
*每个皇后不能在同一行,不能在同一列,也不能在对角线
* 同一行:每行只放置一个皇后
*不能在同一列:使用标志数组,如果当前列的值为true表示不可放置
* 不能再对角线:同样使用标志数组,如果为false则表示已被占领,不可放置
* 上对角线:行-列+7
* 下对角线:行+列
* */
public class test18 {
// 皇后所在的位置
static int[] place = new int[8];
// 标志数组, true为不可放置
static boolean[] notPlaceable = new boolean[8];
// 存储结果数量
static int[] sum = {0};
// d1数组存储上对角线,d2数组存储下对角线,false认为对角线上有皇后,不可以占领
static boolean[] d1 = {true, true, true, true, true, true, true, true, true, true, true, true, true, true,true};
static boolean[] d2 = {true, true, true, true, true, true, true, true, true, true, true, true, true, true,true};
// 8皇后具体算法
private static void generate(int n){
// 每个皇后都有8种可能的列
for (int col = 0; col < 8; col++) {
// 判断是否可以放置
if(!notPlaceable[col] && d1[n-col+7] && d2[n+col]){
//行数是一个自然递增的过程,我们只需要判断其列
place[n] = col; // 在 n 行 col 列摆放皇后
notPlaceable[col] = true; // 占领该列
d1[n-col+7] = false; // 占领上对角线
d2[n+col] = false; // 占领下对角线
if(n < 7)
generate(n+1);//递归算法----递归7次之后求得一种结果8个皇后所在的位置
else{
sum[0]++; // 解的个数加1
myPrint(); // 打印一种结果
}
// 回溯用于求其他结果
notPlaceable[col] = false;
d1[n-col+7] = true;
d2[n+col] = true;
}
}
}
// 打印每种结果
private static void myPrint(){
for (int i = 0; i < place.length; i++) {
System.out.print(place[i]+1 + " "); // 打印结果直接是第几列
}
System.out.println();
}
// 主函数
public static void main(String[] args) {
generate(0); // 求解8皇后
System.out.println("共有的解法: " + sum[0]);
}
}
八皇后问题~
最新推荐文章于 2024-09-20 15:32:13 发布