皇后的JAVA版

来源:互联网 发布:全球交易助手 mac 编辑:程序博客网 时间:2024/04/30 09:14
public class queens {
    
static int q=10;
    
static int[] i=new int[q];
    
static int count=0;
    
public static void main(String[] args){
        
long t = System.currentTimeMillis();
        scan(
0);
        System.out.println(
"totle results:"+count);
        System.out.println(
"totle time:"+(System.currentTimeMillis()-t));
    }

    
private static void scan(int n){
        
if (n==q){
//            for (int k=0;k<q;k++) System.out.print(i[k]+(k==q-1?" ":","));
            count++;
            
return;
        }

        i[n]
=0;
        
while(i[n]<q){
            i[n] 
= i[n]+1;
            
if (check(n)){
                scan(n
+1);
            }

        }

    }

    
private static boolean check(int n){
        
for(int j=0;j<n;j++){
            
if (i[j]==i[n] || i[j]-i[n]==j-|| i[j]-i[n]==n-j ){
                
return false;
            }

        }

        
return true;
    }

}