您的位置:首页 > 编程语言

一个八皇后问题代码实现

2014-11-02 20:53 330 查看
求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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: