八皇后问题介绍
代码
package com.afmobi;
public class Queue8 {
int max = 8; // 多少个皇后
int[] array = new int[max]; // 保存皇后位置的结果
static int count;
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
queue8.pushQueue(0);
System.out.printf("一共有%d解法", count);
}
// 放置第n个皇后
public void pushQueue(int n) {
if (n == max) { // 全部放好皇后
print();
return;
}
// 依次放入皇后
for (int i = 0; i < max; i++) {
// 把当前皇后放到该行的 各个列上(从第一列开始) i;
array[n] = i;
if (judge(n)) {
pushQueue(n + 1); //递归调用
}
}
}
// 查看当我们放置第n个皇后,就去检查该皇后是否和前面已经摆好的皇后冲不冲突
/**
* @Description: @param: @param n 表示第n个皇后 @param: @return @return:
* boolean @throws
*/
public boolean judge(int n) {
for (int i = 0; i < n; i++) {
// 这里不需要判断在同一行的原因就是 ,n每次都在递增,根本不会在同一行
if (array[i] == array[n] // 皇后在同一列
|| Math.abs(n - i) == Math.abs(array[n] - array[i])) { // 在同一个斜线
return false;
}
}
return true;
}
// 输出皇后位置
public void print() {
count ++;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
}
运行结果