Java实现N皇后_N皇后问题(Java版)

/**

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

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值