八皇后问题
在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法
package recursion;
public class Queue8 {
// 表示有多少个皇后
int max = 8;
// 皇后位置的结果
int[] array = new int[max];
static int count = 0;
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
queue8.check(0);
System.out.println("解法"+count);
}
public void check(int n) {
if (n == max) {
count++;
print();
return;
}
for (int i = 0; i < max; i++) {
array[n] = i;
if (judge(n)){
check(n+1);
}
}
}
// 当放置第n个,检测是否跟前面矛盾
public boolean judge(int n) {
for (int i = 0; i < n; i++) {
if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {
return false;
}
}
return true;
}
public void print() {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
}