求n皇后总共的摆放方案
import java.util.Scanner;
public class NQueen1 {
static int n;
static int[] x;
static long sum;
//初始化棋盘
public static long nQueen(int nn){
n = nn;
sum = 0;
x = new int [n+1];
for (int i = 0; i <= n; i++) x[i] = 0;
backtrack(1);
return sum;
}
//判断下一步是否在其它皇后的攻击范围之内
private static boolean place(int k){ //试探第k行行不行
for (int j = 1; j < k; j++)
if((Math.abs(k-j) == Math.abs(x[j]-x[k]))||(x[j] == x[k])) //(在不在斜对角线上||在不在同一列)
return false;
return true;
}
//回溯法的递归框架
private static void backtrack(int t){ //t代表当前行数
if(t>n) sum++;
else
for (int i = 1; i <= n; i++) {
x[t] = i; //x[t]代表当前列数
if(place(t)) backtrack(t+1); //符合约束函数就开始递归,否则尝试下一行,i++
}
}
//主函数
public static void main(String[] args) {
System.out.println("请输入棋盘大小:");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
nQueen(a);
System.out.println("皇后的摆放方法有" + sum + "种");
}
}