八皇后问题

问题:

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

思路:

因为棋盘的长宽和皇后的个数是一样的,那么,每一个皇后总是占据其中的一列(或者一行,我们这里假设皇后占据的是列,所以,第i个皇后总是在第i列上)。但是每一个皇后在行上面有很多种不同的位置,如果我们用一个数组row[i]来表示第i个皇后所处的行的位置,那么第i个皇后的坐标为(row[i], 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个皇后,直到,所有的皇后都在棋盘上了。 代码中count指的是皇后的个数。

 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(row);//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     }

代码其它部分:

 1 public class BackDateQueen{
 2     
 3     //r[i] refers to the ith queen's row position。
 4     // count refers to the number of queens
 5     private int count = 0;
 6     // times refers to how many possible cases
 7     private int times;
 8     
 9     //constructor
10     public BackDateQueen(int count){
11         times = 0;
12         this.count = count;
13     }
14     
15     public static void main(String[] args){
16         BackDateQueen bdq=new BackDateQueen(4);
17         int[] row = new int[4];
18         
19         //no queen on the board
20         for (int i = 0; i < 4; i++) {
21             row[i] = -1;
22         }
23         bdq.queen(0, row);
24     }
25 }

参考:

http://blog.csdn.net/lixiaoshan_18899/article/details/1286716

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

posted @ 2015-01-02 06:06  北叶青藤  阅读(212)  评论(0)    收藏  举报