递归:
public class eightQueue {
static int record[] = new int[8];
static int num = 0;
static int N = 8;
public static void main(String []args){
System.out.println("start*********");
if(args.length != 0){
N = Integer.parseInt(args[0]);
}
findQueue(0);
System.out.println(num);
}
public static void findQueue(int row){
if(row == N){
num++;
System.out.println("找到第" + num + "个。。。");
return;
}else {
for (int col = 0; col < N; col++) {
if (checkQueue(row, col)) {
record[row] = col;
findQueue(row + 1);
}
}
}
}
public static Boolean checkQueue(int row, int col){
for(int i=0; i<row; i++){
if(record[i] == col || Math.abs(i-row) == Math.abs(col - record[i])){
return false;
}
}
return true;
}
}
非递归:
public class eightQueue2 { static int record[] = new int[8]; static int num = 0; static int N = 8; public static void main(String []args) { findQueue(); System.out.println(num); } public static void findQueue(){ init(); //非递归的话,假如从第0个皇后开始,到第7个皇后,然后逆推第6个皇后的其他位置,然后。。。然后到第0个皇后的下一个位置, //反复循环 for(int row = 0; row >= 0; ){ record[row]++;//此时是从0开始的,即1-8列,与下面的N对应,不然就是N-1 if(record[row] == N){ //假如第row个皇后的位置到达了8列,说明依然检索完当前皇后,逆推到上一个皇后,标记清零 record[row] = -1; row--; continue; } if(checkQueue(row, record[row])){ //假如第row个皇后的当前位置与前row个皇后不冲突 //可以查找下一个皇后了 row++; if(row==N){ //假如第N-1个符合,即第7个皇后符合,即最后一个皇后,计数加1,然后逆推道倒数第二个, num++; record[row-1] = -1; row = N-2; } } } } public static void init(){ for(int i = 0; i < N; i++){ record[i] = -1; } }
public static Boolean checkQueue(int row, int col){ for(int i=0; i<row; i++){ if(record[i] == col || Math.abs(i-row) == Math.abs(col - record[i])){ return false; } } return true; } }