/**
* n queens problem
*
* */
public class EightQueen {
private int QUEEN_COUNT = 0;//represent the queen count
private int[][] queenCount;//chess box matrix
private int resultCount = 0;//solution number
private int[] queenPlace;//mark the queen placed position
/**
* construct a EightQueen with a argument represent the number of queen
* initial a empty chess box
* 0 represent empty
* 1 represent the area has been taken
* recurse to call the putQueen method
* the queenPlace array to mark the queen's taken area which uses to print
*
* */
public EightQueen(int n) {
this.QUEEN_COUNT = n;
this.resultCount = 0;
this.queenCount = new int[QUEEN_COUNT][QUEEN_COUNT];
queenPlace = new int[QUEEN_COUNT];
putQueen(0);
}
/**
* implement the putQueen function to recursion
* use column index in outer loop and row index in inner loop with step increase
* */
private void putQueen(int row) {
for (int column = 0; column < QUEEN_COUNT; column++) {//loop for QUEEN_COUNT times
if (queenCount[row][column] == 0) {//judge the condition
/**
* each row has one queen
* mark the column and diagonal back diagonal(row has been scatter)
*
* */
for (int nextRow = row + 1; nextRow < QUEEN_COUNT; nextRow++) {
queenCount[nextRow][column]++;
if (column - nextRow + row >= 0) {
queenCount[nextRow][column - nextRow + row]++;
}
if (column + nextRow - row < QUEEN_COUNT) {
queenCount[nextRow][column + nextRow - row]++;
}
}
queenPlace[row] = column;//place the queen with only column information
if (row == QUEEN_COUNT - 1) printQueen(++resultCount);//recursion has completed
else putQueen(row + 1);//recurse to call the putQueen function
/**
*
* unmarked the column and diagonal back diagonal(row has been scatter)
*
* */
for (int rows = row + 1; rows < QUEEN_COUNT; rows++) {
queenCount[rows][column]--;
if (column - rows + row >= 0) {
queenCount[rows][column - rows + row]--;
}
if (column + rows - row < QUEEN_COUNT) {
queenCount[rows][column + rows - row]--;
}
}
}
}
if (row == 0) System.out.println(QUEEN_COUNT + " queens has totally " + resultCount + "result.");
}
private void printQueen(int size)
{
System.out.println("********** "+size+" **********\n");
for (int i = 0; i < QUEEN_COUNT; i++) {
for (int j = 0; j < QUEEN_COUNT; j++) {
System.out.print(queenPlace[i] == j ? " # " : " - ");
}
System.out.println();
}
}
}
N皇后问题(Java版)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 最近,刘晓庆好像因为什么事情去了重庆一趟。既然到了重庆,那肯定是要尝一尝重庆的特色火锅,这才不算是白来一趟啊。 昨...
- 题目描述 The n-queens puzzle is the problem of placing n quee...