找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3956|回复: 0

八皇后问题 |beiyeqingteng

[复制链接]
发表于 2011-12-14 14:04:58 | 显示全部楼层 |阅读模式
问题:
8
×
8
的国际象棋上摆放八个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列或者同一对角斜线上。请求出总共有多少种摆法。下图为一种为符合条件的摆放。


思路:
因为棋盘的长宽和皇后的个数是一样的,那么,每一个皇后总是占据其中的一列(或者一行,我们这里假设皇后占据的是列,所以,第i个皇后总是在第i列上)。但是每一个皇后在行上面有很多种不同的位置,如果我们用一个数组row来表示第i个皇后所处的行的位置,那么第i个皇后的坐标为(row, i)。这里,我们认为皇后的编号从0开始。
因为条件要求“任意两个皇后不得处在同一行、同一列或者同一对角斜线上”。假如,我们放皇后是从0开始,然后放1,,,,一直到7。那么,我们放第i个皇后的时候,前面i-1个皇后其实已经放好了,而且都满足条件,那么放第i个皇后的时候,我们只需要看第i个皇后的位置是否和前面的i-1个皇后满足相应的条件,因为皇后都放在不同的列上,所以,我们只需要考虑是否在同一行或者在同一斜线上。代码如下:
  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
  2.         public boolean isSatisfied(int n, int[] row){
  3.                 for(int i = 0; i < n; i++){
  4.                         //on the same row
  5.                         if(row[i] == row[n]) return false;
  6.                         //on the same oblique line(斜线)
  7.                         if(Math.abs(row[n] - row[i]) == n - i) return false;
  8.                 }
  9.                 return true;
  10.         }
复制代码
有了这样一个判断的方法,我们只需要把第i个皇后放在第从0到7的任意一行(for loop),然后,把第i个皇后与前面i-1个皇后的位置进行比较,如果满足,再放第i+1个皇后,直到,所有的皇后都在棋盘上了。
  1.   // the main method to find all the possible cases. n refers to the n-th queens.
  2.         public void queen(int n, int[] row){
  3.                 if (n == count) {
  4.                         times++;
  5.                         print();//print
  6.                         return;
  7.                 }
  8.                
  9.                 //put the nth queen to all the possible position
  10.                 for(int i = 0; i < count; i++){
  11.                         row[n] = i;        //put the nth queen to the row i.
  12.                         if(isSatisfied(n, row)) {
  13.                                 queen(n+1, row);
  14.                         }
  15.                 }
  16.    }
  17.         //print the successful case
  18.         public void print(int[] row){
  19.                 System.out.println("the "+times+"th successful case");
  20.                 for(int i = 0; i < count; i++){
  21.                         System.out.println("the "+i+"th column, the "+row[i]+"th row");
  22.                 }
  23.         }
复制代码
参考:http://blog.csdn.net/lixiaoshan_18899/article/details/1286716
http://zhedahht.blog.163.com/blog/static/2541117420114331616329/

作者:beiyeqingteng 发表于2011-12-14 6:52:03 原文链接
您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-29 14:39 , Processed in 0.012087 second(s), 5 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表