八皇后问题
一、源代码
package recurtion;
//八皇后问题
public class Queue8 {
//定义一个一维数组,其中数组的第几个数为第几个黄后应该摆放的位置,而值为摆放的列数
int max = 8;
int[] array = new int[max];
static int count = 0;
//打印这个数组的方法
public void print() {
for (int i = 0; i < array.length; i++) {
System.out.printf(array[i] + " ");
}
System.out.println();
}
/**
*
* @param n 第几个皇后
* @return
*/
//判断放置的皇后是不是在同一列或者对角线,因为是按顺序放置,因此不可能在同一行
public boolean judge(int n) {
for (int i = 0; i < n; i++) {
//从第一个皇后开始,到第n个
//因为array[n] == array[i]是判断是不是在同一列
//Math.abs(n - i) == Math.abs(array[n] - array[i]判断是不是在对角线上,因为是正方形,所以构成一个三角形(对角线、行、列)
if (array[n] == array[i] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
return false;
}
}
return true;
}
/**
*
* @param n 第几个皇后
*/
//进行摆放8皇后
public void check(int n){
//如果n已经达到max则说明遍历完成了
if (n==max){
count++;
print();
return;
}
//一次放入8个皇后,看是否冲突
for (int i =0; i<max;i++){
array[n] =i;
if (judge(n)){
check(n+1);
}
}
}
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
queue8.check(0);
System.out.println("有多少种解答方法:"+ count);
}
}
总结
每次回溯都会进入循环阶段,每一行中的每一个位置都会进行判断。