/**
* Created by tianhongyan on 18/4/7.
*/
public class EightQueenSettlement {
public static final int MAX_COUNT = 8;
public int settleCount;
int chessBoard[][] = new int[MAX_COUNT][MAX_COUNT];
public boolean check(int x, int y){
if(y==0){
return true;
}
for(int i=1; i <= y; i++){
//纵向上是否可以摆放
if(chessBoard[x][y-i] == 1){
return false;
}
//左上方是否可以摆放
if(x-i >= 0 && y-i >=0 && chessBoard[x-i][y-i] == 1){
return false;
}
//右上方是否可以摆放
if(x+i < MAX_COUNT && y-i >= 0 && chessBoard[x+i][y-i] == 1){
return false;
}
}
return true;
}
public void settleQueen(int n){
if(n >= MAX_COUNT){
return ;
}
for(int i=0; i<MAX_COUNT; i++){
for(int j=0;j<MAX_COUNT;j++){
chessBoard[j][n] = 0;
}
if(n == MAX_COUNT-1){
if(check(i,n)){
chessBoard[i][n] = 1;
settleCount++;
printChessBoard(settleCount);
}
if(i>= MAX_COUNT){
break;
}
}else {
if (check(i,n)) {
chessBoard[i][n] = 1;
settleQueen(n + 1);
}
}
}
}
public void printChessBoard(int settleCount){
System.out.println("第 "+settleCount +"种");
for(int i=0; i<MAX_COUNT; i++){
for(int j=0; j<MAX_COUNT; j++){
System.out.print(chessBoard[i][j]+" ");
}
System.out.println();
}
System.out.println("===============");
}
public static void main(String[] args){
EightQueenSettlement eightQueen = new EightQueenSettlement();
eightQueen.settleQueen(0);
}
}
[数据结构]八皇后问题 棋盘 java实现
猜你喜欢
转载自blog.csdn.net/tianhongyan1122/article/details/79840350
今日推荐
周排行