package 习题;
public class 八皇后 {
static int c[] = new int[8];
static int total = 0;
public static void main(String[] args) {
queen(0);
System.out.println(total);
}
public static void queen(int row) {
if(row==8) { //找到一个解
total++;
/*for(int i=0;i<8;i++)
System.out.print(c[i]+" ");
System.out.println();*/
}
else {
for(int col = 0;col < 8;col++) {
c[row] = col;
if(isOk(row)) {
queen(row+1);
}
}
}
}
public static boolean isOk(int row) { //看看这一列能否放皇后
for(int i = 0;i < row;i++) {
if(c[row] == c[i] || row-c[row] == i-c[i] || row+c[row] == i+c[i]) { //列相同,对角线相同;对角线定律:行-列=行-列 或 行+列=行+列
return false;
}
}
return true;
}
}