package com.zsx.algorithm;
/**
* @author Zsx
* 八皇后问题
* @Time 2021/6/15 20:48
*/
public class Queue8 {
//表示共有max个皇后
int max = 8;
//结果
// 一维数组表示
int[] result = new int[max];
//结果次数
int count = 0;
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
queue8.check(0);
}
//放置第n个皇后
public void check(int n) {
//放完,结束
if (n == max) {
printResult();
return;
}
for (int i = 0; i < max; i++) {
//把当前皇后放到第一列
result[n] = i;
//判断
if (judge(n)) {
//不冲突
//继续放n+1
check(n + 1);
}
//冲突 --> 则继续执行循环
}
}
/**
* 打印结果
*/
public void printResult() {
System.out.println("----------------------第" + (++count) + "个结果----------------------");
// ①结果展示在二维数组上
int[][] array = new int[max][max];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (j == result[i]) {
array[i][j] = 1;
}
}
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
//②结果展示在一维数组上
// for (int i = 0; i < result.length; i++) {
// System.out.print(result[i] + " ");
//
//
// }
System.out.println();
}
/**
* 检测是否和前面摆放的冲突
*
* @param n 第n个皇后
* @return
*/
public boolean judge(int n) {
for (int i = 0; i < n; i++) {
//在同一列上
if (result[i] == result[n]) {
return false;
}
//在同一斜线上
if (Math.abs(n - i) == Math.abs(result[i] - result[n])) {
return false;
}
}
return true;
}
}