/**
*
*/
package com.pro.recursion;
/**
* @Description
* @author kansir
* @version
* @date 2019年8月10日 上午10:08:15
*/
public class EightQueens {
//定义一个max表示共有多少个皇后
int max=8;
//定义数组,保存皇后放置位置的结果,比如arr={0,4,7,5,2,6,1,3}
int[] array=new int[max];
static int count=0;
static int judgeCount=0;
public static void main(String[] args) {
EightQueens eightQueens=new EightQueens();
eightQueens.check(0);
System.out.println("一共有:"+count+"种解法");
System.out.println("一共有:"+judgeCount+"次判断");
}
//放置第n个皇后
/**
*
* @Description 放置第n个皇后,注意:每个check中都有for循环,因此会产生回溯
* @author kansir
* @date 2019年8月10日 上午10:39:18
* @param n
*/
public void check(int n) {
if(n==max) {//n==8,其实8个皇后就已经放好了
print();
return;
}
//依次放入皇后,并判断是否冲突
for (int i = 0; i < max; i++) {
//先把当前这个皇后放到改行的第一列
array[n]=i;
//判断当放置第n个皇后到第i列时是否冲突
if(judge(n)) { //如果不冲突
//接着放第n+1个皇后,开始递归\
check(n+1);
}else {//如果冲突,就继续执行array[]=i;即将第n个皇后,放置在本行的后移一个位置
}
}
}
/**
*
* @Description 查看当我们的位置放第n个皇后,就去检测该黄后是否和前面已经摆放的皇后冲突
* @author kansir
* @date 2019年8月10日 上午10:16:43
* @param n 表示第n个皇后
* @return
*/
public boolean judge(int n) {
judgeCount++;
for (int i = 0; i < n; i++) {
//如果array[i]==array[n]说明第n个皇后和前面n-1个皇后在同一列
//Math.abs(n-1) ==Math.abs(array[n]-array[i]) 表示判断第n个皇后是否和第i个皇后在同一斜线
if(array[i]==array[n]||Math.abs(n-i) ==Math.abs(array[n]-array[i])) {
return false;
}
}
return true;
}
/**
*
* @Description 将皇后摆放的位置打印出来
* @author kansir
* @date 2019年8月10日 上午10:14:13
*/
public void print() {
count++;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
}
}