在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。
答案是:92种。
下面贴代码:
public class EightQueen {
int sum = 0;
public static final int MAX = 8;
public void showResult(int[] result) {
for (int i = 0; i < result.length; i++) {
System.out.print((i+1) + "行" + (result[i]+1)+"列 ");
}
System.out.println();
sum++;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] result = new int[MAX];
EightQueen queen = new EightQueen();
queen.queen(result, 0);
System.out.println("total:" + queen.sum);
}
/* 检查当前行 x 放置的皇后是否正确 */
private boolean check(int[] result, int x) {
for (int i = 0; i < x; i++) { //遍历前面的 x-1 行放好的皇后,看是否与 x 行的这个冲突
if (result[i] == result[x]
|| (Math.abs(result[i] - result[x]) == Math.abs(i - x))) {
return false;
}
}
return true;
}
/* 回溯尝试皇后位置,n为横坐标 */
private void queen(int[] result, int x) {
if(x == MAX){
showResult(result); //一共有MAX列,从0开始,所以已近排完,打印结果
return;
}
// 新的一行里面,皇后可以在任何位置:0->max,所以i=0->max,而不是i=n->max
for(int i = 0; i<MAX ; i++){
result[x] = i; //x行的第i列放置皇后
if(check(result,x)){
queen(result, x+1); //如果这个位置可以,就再继续下一行
}
//如果不可以,就换成这行的下一个列的位置
}
}
}