public class Queue8 {
//棋子数量
int max = 8;
//棋子最后所排的顺序
int [] arr = new int[max];
//计有效次数
static int count = 0;
//无效次数
static int run = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue8 q = new Queue8();
q.setchess(0);
System.out.println("一共有"+count+"解法!");
System.out.println("一判断"+run+"次!");
}
//放置棋子
public void setchess(int n) {
if(n == max) {
print();
count++;
return;
}
for(int i = 0;i < 8;i++) {
arr[n] = i;
//判断这个位置是否有效
if(check(n)) {
//开始递归
setchess(n+1);
}
}
}
//判断棋子是否合理
/**
*
* @param n 第几个棋子
* @return
*/
public boolean check(int n) {
run++;
//1.判断是否在同一列
//2.判断是否在一条斜线上
for(int i = 0;i < n;i++) {
if(arr[n] == arr[i] || Math.abs(n-i)==Math.abs(arr[i]-arr[n])){
return false;
}
}
return true;
}
//打印
public void print() {
for(int i = 0;i < arr.length;i++) {
System.out.print(arr[i]+" ");
}
System.out.println("\n");
}
}
结果