java一个八皇后问题代码实现



java一个八皇后问题代码实现.

求8*8的棋盘有多少皇后位置方式。

 

 

  1. public class Empress {
  2.     private int n ;
  3.     private int[] x ;
  4.     private long sum ;
  5.     private static int h ;
  6.     public Empress(){
  7.         this.sum = 0 ;
  8.         this.n = 8 ;
  9.         this.x = new int[n+1];
  10.         h = 1 ;
  11.     }
  12.     public boolean place (int k){
  13.         for (int j = 1 ; j < k ; j++){
  14.             if ( (Math.abs(k - j)) == (Math.abs(x[j]-x[k])) || (x[j] == x[k]) ){
  15.                 return false ;
  16.             }
  17.         }
  18.         return true ;
  19.     }
  20.     public void backTrace (int t){
  21.         if (t > n){
  22.             sum ++ ;
  23.         }else {
  24.             for (int i = 1 ; i <= n ; i++){
  25.                 x[t] = i ;
  26.                 if (place (t)){
  27.                     backTrace (t+1);
  28.                 }
  29.             }
  30.         }
  31.     }
  32.     public long getAllValidNumbers(){
  33.         backTrace(1);
  34.         return this.sum;
  35.     }
  36.     public static void main (String[] args){
  37.         Empress em = new Empress();
  38.         System.out.println(em.getAllValidNumbers());
  39.     }
  40. }