您的位置:首页 > 其它

"八皇后"问题的解法(1)

2015-05-21 16:36 99 查看
最近准备整理5种常见的"八皇后"问题的解法,这是第一篇,用递归方法求解。

简单介绍下"八皇后"问题:如何在8*8棋盘上无冲突放置8个皇后,无冲突可按如下理解(1)任何水平或竖直方向不能再有其他皇后;(2)正负45‘方向不能再有皇后;

源代码如下:

/*
2015.5.21 by HanChun http://blog.csdn.net/code_7 */

public class Queen {
private static int count = 0;   //记录解的个数

public static void main(String[] args) {
int[][] chessboard1 = new int[8][8];
//初始化棋盘
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
chessboard1[i][j] = 0;
}
}
solveQue(0, 8, chessboard1);
System.out.println("八皇后解的个数为:" + count);

}

public static int solveQue(int row, int col, int[][] chessboard){
int[][] chessboard2 = new int[8][8];
//复制chessboard留做后面递归使用
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
chessboard2[i][j] = chessboard[i][j];
}
}
if(row==8){
System.out.println("这是第" + (count+1) + "种解法");
for(int i=0; i<chessboard2.length; i++){
for(int j=0; j<chessboard2[i].length; j++ ){
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
count++;
}else{
for(int j=0; j<col; j++){
if(!isPlaced(row, j, chessboard)){
for(int k=0; k<8; k++){
chessboard2[row][k] = 0;
}
chessboard2[row][j] = 1;
solveQue(row+1, col, chessboard2);
}
}
}
return count;
}

public static boolean isPlaced(int row, int col, int[][] chessboard){
boolean flag1=false, flag2=false, flag3=false, flag4=false, flag5=false;
//检查列是否有冲突
for(int i=0; i<8; i++){
if(chessboard[i][col] == 1){
flag1 = true;
break;
}
}
//检查左上是否有冲突
for(int i=row, j=col; i>=0 && j>=0; i--,j--){
if(chessboard[i][j] == 1){
flag2 = true;
break;
}
}
//检查右上是否冲突
for(int i=row, j=col; i>=0 && j<8; i--,j++ ){
if(chessboard[i][j] == 1){
flag3 = true;
break;
}
}
//检查右下是否有
for(int i=row, j=col; i<8 && j<8; i++,j++ ){
if(chessboard[i][j] == 1){
flag4 = true;
break;
}
}
//检查左下是否有冲突
for(int i=row, j=col; i<=0 && j>=0; i++,j-- ){
if(chessboard[i][j] == 1){
flag5 = true;
break;
}
}
if(flag1||flag2||flag3||flag4||flag5){
return true;
}
return false;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐