初学JAVA,一个八皇后问题求解
我写的一个八皇后小程序,运行木有结果..纠结中,,求帮忙呀....
public class Empress {
private int top ; //栈顶指针
private int [] stack ; //用来模拟栈结构的一个数组
private int n ; //解决皇后问题的个数,默认为8个
private long sum ;
private static int h ;
public Empress (){//初始化问题
this.top = 1 ;
this.n = 8 ;
this.stack = new int[n+1];
this.h = 1;
this.sum = 0 ;
for(int i = 0 ; i<stack.length ; i++){
stack[i]=0;//0表示不放棋子,i表示在第i行,stack[i]表示列数
}
// backTrace();//开始回溯
}
public boolean place(int k){
int i = 1 ;
while( k >= i ){
if ( (Math.abs(k - i)) == (Math.abs(stack[k]-stack[i])) || (stack[k] == stack[i]) ){
return false ; //如果是与之同一行同一列的或同一斜线上的棋子,返回false;
}
i++;
}
return true ;
}
public void backTrace(){
for(int i = 1 ; i <= n ; i++){
stack[top] = i ;
if(place (top) && top >= n){
sum ++ ; //方案数自增1
System.out.println ("方案" + (h++) + "");
}else if(place (top) && top < n){//得到一个互不攻击的皇后序列且栈未满,继续入栈重新判断
i = 0 ;
top ++ ;
continue ;
}else if (!place(top) && top < n){
continue;
}else{//得到的序列互相攻击,而且列数到8,执行回溯操作:栈顶元素出栈,然后下一个栈顶元素在循环作用下自增继续判断
stack[top --] = 0;
continue ;
}
}
}
public static void main(String [] args ) {
new Empress().backTrace();
}
}