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

最近准备整理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;
	}

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值