0-空白位置,1-皇后,2-不能放置皇后的位置
每次复制一个上一次传递的数组,在line行找到一个空白位置放置皇后,将此皇后的行、列和斜线都赋值为2,循环。
import java.util.Arrays;
public class EightQueen {
public static final int NORMAL = 0;// 当前位置可以放Queen
public static final int QUEEN = 1;// 当前位置放置了Queen
public static final int DISABLE = 2;// 当前位置不能放置Queen
public static final int LENGTH = 8;
public static void main(String[] args) {
EightQueen eightQueen = new EightQueen();
eightQueen.start();
}
void start() {
eightQueen(new int[LENGTH][LENGTH], 0);
}
int index = 0;
/**
* @param src
* 八皇后的棋盘,8x8
* @param line
* 当前第几行,从0开始
*/
void eightQueen(int[][] src, int line) {
if (line >= LENGTH) {
// find
index++;
System.out.println("结果===================" + index);
printArray(src);
} else {
for (int i = 0; i < LENGTH; i++) {
// 创建一个新数组用于next
int[][] next = new int[LENGTH][];
for(int j = 0;j < LENGTH;j++) {
next[j] = Arrays.copyOf(src[j], src[j].length);
}
if (next[line][i] == NORMAL) {
next[line][i] = QUEEN;
// 标记和当前位置冲突的位置为DISABLE
// 标记一行
for (int j = 0; j < LENGTH; j++) {
if (j != i) {
next[line][j] = DISABLE;
}
}
// 标记一列
for (int j = 0; j < LENGTH; j++) {
if (j != line) {
next[j][i] = DISABLE;
}
}
// 标记斜线
int min = Math.min(line, i);
for (int row = line - min, col = i - min; row < LENGTH
&& col < LENGTH; row++, col++) {
if (row != line && col != i) {
next[row][col] = DISABLE;
}
}
min = Math.min(line, LENGTH - i - 1);
for (int row = line - min, col = i + min; row < LENGTH
&& col >= 0; row++, col--) {
if (row != line && col != i) {
next[row][col] = DISABLE;
}
}
eightQueen(next, line + 1);
}
}
}
}
static void printArray(final int[][] array) {
for (int[] line : array) {
for (int i : line) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
}
}
}