import java.util.*;
/**
* 八皇后问题
* @author oracs
* @date 2008-06-04
*/
public class EightQueens {
private static final int N = 8;
private int[] queen = new int[N];
private int count = 0;
// constructor
public EightQueens() {
for (int i = 0; i < N; i++) {
queen[i] = -1;
}
}
/**
* @param args
*/
public static void main(String[] args) {
EightQueens q = new EightQueens();
q.findQueen(0);
}
public boolean isQueenAtChest(int i, int j) {
boolean result = false;
if (j == 0) { // init queen array
queen[0] = i;
return true;
}
else {
// loop queen array, find whether the next queen is in the right positon
for (int queen_col = 0; queen_col < queen.length; queen_col++) {
int queen_row = queen[queen_col];
if ( queen_row != -1) {
if ( (i == queen_row) // 同一横线
||((i >= queen_row) && (i == j + (queen_row - queen_col))) // 主对角线
||((i < queen_row) && (i == (queen_row + queen_col) - j))) { // 斜对角线
return false;
}
}
if (queen_col == queen.length - 1) {
queen[j] = i;
return true;
}
}
}
return result;
}
public void findQueen(int col) {
if (col < N) {
// loop every row in col
for (int row = 0; row < N; row++) {
if (isQueenAtChest(row, col)) {
// recursion
findQueen(col+1);
}
}
// print the queen
if (col == N - 1) {
printQueen();
}
// clear queen
clearQueen(col);
}
}
// print queen
public void printQueen() {
for (int i = 0; i < queen.length; i++) {
if (queen[i] == -1) return;
}
System.out.println(++count +":" + Arrays.toString(queen));
}
// initial -1 to queen 's back position
public void clearQueen(int col) {
for (int i = col; i < N; i++) {
queen[i] = -1;
}
}
}
八皇后问题
最新推荐文章于 2022-10-14 23:24:33 发布