八皇后问题 [No. 59]

问题:

8×8的国际象棋上摆放八个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。请求出总共有多少种摆法。下图为一种为符合条件的摆放。


思路:

因为棋盘的长宽和皇后的个数是一样的,那么,每一个皇后总是占据其中的一列(或者一行,我们这里假设皇后占据的是列,所以,第i个皇后总是在第i列上)。但是每一个皇后在行上面有很多种不同的位置,如果我们用一个数组row[i]来表示第i个皇后所处的行的位置,那么第i个皇后的坐标为(row[i], i)。这里,我们认为皇后的编号从0开始。

因为条件要求“任意两个皇后不得处在同一行、同一列或者同一对角斜线上”。假如,我们放皇后是从0开始,然后放1,,,,一直到7。那么,我们放第i个皇后的时候,前面i-1个皇后其实已经放好了,而且都满足条件,那么放第i个皇后的时候,我们只需要看第i个皇后的位置是否和前面的i-1个皇后满足相应的条件,因为皇后都放在不同的列上,所以,我们只需要考虑是否在同一行或者在同一斜线上。代码如下:

//compare the n-th queen's row position with the previous (n-1) queen's row position,n refers to the n-th queen
	public boolean isSatisfied(int n, int[] row){
		for(int i = 0; i < n; i++){
			//on the same row
			if(row[i] == row[n]) return false;
			//on the same oblique line(斜线)
			if(Math.abs(row[n] - row[i]) == n - i) return false; 
		}
		return true;
	}
有了这样一个判断的方法,我们只需要把第i个皇后放在第从0到7的任意一行(for loop),然后,把第i个皇后与前面i-1个皇后的位置进行比较,如果满足,再放第i+1个皇后,直到,所有的皇后都在棋盘上了。 代码中count指的是皇后的个数。

代码核心部分:

  // the main method to find all the possible cases. n refers to the n-th queens.
	public void queen(int n, int[] row){
		if (n == count) {
			times++;
			print(row);//print
			return;
		}
		
		//put the nth queen to all the possible position
		for(int i = 0; i < count; i++){
			row[n] = i;	//put the nth queen to the row i. 
			if(isSatisfied(n, row)) {
				queen(n+1, row);
			}
		}
   }
	//print the successful case
	public void print(int[] row){
		System.out.println("the "+times+"th successful case");
		for(int i = 0; i < count; i++){
			System.out.println("the "+i+"th column, the "+row[i]+"th row");
		}
	}

代码其它部分:

public class BackDateQueen{
	
	//r[i] refers to the ith queen's row position。
	// count refers to the number of queens
	private int count = 0;
	// times refers to how many possible cases
	private int times;
	
	//constructor
	public BackDateQueen(int count){
		times = 0;
		this.count = count;
	}
	
	public static void main(String[] args){
		BackDateQueen bdq=new BackDateQueen(4);
		int[] row = new int[4];
		
		//no queen on the board
		for (int i = 0; i < 4; i++) {
			row[i] = -1;
		}
		bdq.queen(0, row);
	}
}
参考: http://blog.csdn.net/lixiaoshan_18899/article/details/1286716

http://zhedahht.blog.163.com/blog/static/2541117420114331616329/

转载请注明出处:blog.csdn.net/beiyeqingteng

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值