Cracking the coding interview--Q8.8

原文:

Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

译文:

经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。


用回溯算法。对于每一行,列,检查皇后不攻击不违反所需的条件。

为此,我们需要存储的列女王在每一行只要我们完成它。让ColumnForRow[]是商店的数组每行的列号。
给出的检查,需要三个条件:
在同一列:ColumnForRow[i]= = ColumnForRow[j]

在同一对角线:(ColumnForRow[i]——ColumnForRow[j])= =(i - j)或(ColumnForRow[j],ColumnForRow[i])= =(i - j),代码如下:


package chapter_8_Recursion;

/**
 * 
 * 经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。
 * 
 */
public class Question_8_8 {
	private static int count = 0;
	private static int colum[] = new int[8];
	
	public static void printMarth() {
		for(int i=0; i< 8; i++) {
			for(int j=0; j<8; j++) {
				if(colum[i] != j) {
					System.out.print(" 0 ");
				} else {
					System.out.print(" 1 ");
				}
			}
			System.out.print("\n");
		}
		System.out.print("\n");
	}
	
	/**
	 * @param row
	 * @param col
	 * @return
	 * 
	 * 检查当前行的当前列会不会和前几行的冲突
	 * 
	 */
	public static boolean checkIsOk(int row, int col) {
		for(int i=0; i< row; i++) {
			if(colum[i] == col || ((row-i) == (col - colum[i]) || (row-i) == (colum[i]-col))) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * @param row
	 * 
	 * 递归判断每行的元素摆放位置
	 * 
	 */
	public static void placeQueen(int row) {
		// 成功完成一次
		if(row == 8) {
			count ++;
			printMarth();
			return;
		}
		// 判断当前行的8列是否可以摆设
		for(int i=0; i< 8; i++) {
			if(checkIsOk(row, i)) {
				colum[row] = i;
				placeQueen(row + 1);
			}
		}
	} 
	
	public static void main(String args[]) {
		placeQueen(0);
		System.out.println("count: " + count);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值