java一个八皇后问题代码实现.
求8*8的棋盘有多少皇后位置方式。
- public class Empress {
- private int n ;
- private int[] x ;
- private long sum ;
- private static int h ;
- public Empress(){
- this.sum = 0 ;
- this.n = 8 ;
- this.x = new int[n+1];
- h = 1 ;
- }
- public boolean place (int k){
- for (int j = 1 ; j < k ; j++){
- if ( (Math.abs(k - j)) == (Math.abs(x[j]-x[k])) || (x[j] == x[k]) ){
- return false ;
- }
- }
- return true ;
- }
- public void backTrace (int t){
- if (t > n){
- sum ++ ;
- }else {
- for (int i = 1 ; i <= n ; i++){
- x[t] = i ;
- if (place (t)){
- backTrace (t+1);
- }
- }
- }
- }
- public long getAllValidNumbers(){
- backTrace(1);
- return this.sum;
- }
- public static void main (String[] args){
- Empress em = new Empress();
- System.out.println(em.getAllValidNumbers());
- }
- }