原文:
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.
译文:
经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。
用回溯算法。对于每一行,列,检查皇后不攻击不违反所需的条件。
为此,我们需要存储的列女王在每一行只要我们完成它。让ColumnForRow[]是商店的数组每行的列号。给出的检查,需要三个条件:
在同一列:ColumnForRow[i]= = ColumnForRow[j]
在同一对角线:(ColumnForRow[i]——ColumnForRow[j])= =(i - j)或(ColumnForRow[j],ColumnForRow[i])= =(i - j),代码如下:
package chapter_8_Recursion;
/**
*
* 经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。
*
*/
public class Question_8_8 {
private static int count = 0;
private static int colum[] = new int[8];
public static void printMarth() {
for(int i=0; i< 8; i++) {
for(int j=0; j<8; j++) {
if(colum[i] != j) {
System.out.print(" 0 ");
} else {
System.out.print(" 1 ");
}
}
System.out.print("\n");
}
System.out.print("\n");
}
/**
* @param row
* @param col
* @return
*
* 检查当前行的当前列会不会和前几行的冲突
*
*/
public static boolean checkIsOk(int row, int col) {
for(int i=0; i< row; i++) {
if(colum[i] == col || ((row-i) == (col - colum[i]) || (row-i) == (colum[i]-col))) {
return false;
}
}
return true;
}
/**
* @param row
*
* 递归判断每行的元素摆放位置
*
*/
public static void placeQueen(int row) {
// 成功完成一次
if(row == 8) {
count ++;
printMarth();
return;
}
// 判断当前行的8列是否可以摆设
for(int i=0; i< 8; i++) {
if(checkIsOk(row, i)) {
colum[row] = i;
placeQueen(row + 1);
}
}
}
public static void main(String args[]) {
placeQueen(0);
System.out.println("count: " + count);
}
}