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();
}
}
}