题目
原文:
Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.
译文:
写一个算法打印八皇后在棋盘中所有使任意2个皇后不能处于同一行,同一列或是对角线上的摆法。
解答
这是经典的八皇后问题,首先了解八皇后问题的规则,在8*8国际象棋棋盘上,要求在每一行放置一个皇后,且能做到在竖方向,斜方向都没有冲突。国际象棋的棋盘如下图所示:
用回溯算法。对于每一行,列,检查皇后不攻击不违反所需的条件。
为此,我们需要存储的列女王在每一行只要我们完成它。让ColumnForRow[]是商店的数组每行的列号。给出的检查,需要三个条件:
在同一列:ColumnForRow[i]= = ColumnForRow[j]
在同一对角线:(ColumnForRow[i]——ColumnForRow[j])= =(i - j)或(ColumnForRow[j],ColumnForRow[i])= =(i - j),代码如下:
class Q8_8{
public static int columForRow[]=new int[8];
public static int count=0;
public static boolean check(int row){
for(int i=0;i<row;i++){
int diff=Math.abs(columForRow[i]-columForRow[row]);
if(diff==0||diff==row-i) return false;
}
return true;
}
public static void placeQueen(int row){
if(row==8){
print();
count++;
return;
}
for(int i=0;i<8;i++){
columForRow[row]=i;
if(check(row)){
placeQueen(row+1);
}
}
}
public static void print(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
if(j==columForRow[i]) System.out.print("1 ");
else System.out.print("0 ");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args){
placeQueen(0);
System.out.println(count);
}
}
---EOF---