最近準備整理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;
}
}