N皇后

来源:互联网 发布:删除数据恢复 编辑:程序博客网 时间:2024/04/28 17:08

import  java.io.*;

class Queen{
 int num;//用来计算方案数
 int n;//n皇后
 int [] [] a;
 
 public Queen(int n){
  this.num=0;
  this.n=n;
  a =new int [n][n];
  for(int i=0;i<n;i++)
    for(int j=0;j<n;j++)
      a[i][j]=0;                          
  solve(1);      
 }
 
 public void solve(int x){                
  int col;
  for(col=0;col<n;col++){                               
   if(!isTheSameRow(x-1) && !isTheSameCol(col) && !isdiagonal((x-1),col) && !isundiagonal((x-1),col)){        
         a[x-1][col]=1;//放置皇后                  
      if(x<n ){             
       solve(x+1);
      }
      else {
       num++;       
       System.out.println("皇后摆放第"+num+"种方案:");
       System.out.println("行分别为:"+"1 2 3 4 5 6 7 8");
       System.out.print("列分别为:");
       for(int i=0;i<n;i++)
        for(int j=0;j<n;j++){
         if(a[i][j]==1)
            System.out.print((j+1)+" ");
        }            
       System.out.println();                                            
      }                     
     }      
     a[x-1][col]=0;
  }  
    }
 
 public boolean isTheSameRow(int row){//  判断同行有没有皇后
     boolean flag=false;
  for(int j=0;j<n;j++)
      if(a[row][j]==1){
       flag=true;
       break;
      }
  return flag;
 }
 
 public boolean isTheSameCol(int col){//  判断同列有没有皇后
     boolean flag=false;
  for(int i=0;i<n;i++)
      if(a[i][col]==1){
       flag=true;
       break;
      }
  return flag; 
 }
 
 public boolean isdiagonal(int row,int col){//    判断正反斜线上有没有皇后
  boolean flag=false;
     while(col<n && row>=0){
    if(a[row][col]==1){
     flag=true;
     break;
    }
    col++;
    row--;
     }     
  return flag;
 }
 
 public boolean  isundiagonal(int row,int col){//  判断反斜线上有没有皇后
  boolean flag=false;
     while(col>=0 && row>=0){
    if(a[row][col]==1){
     flag=true;
     break;
    }
    col--;
    row--;
     }     
  return flag;
 }
}

class Test{
 public static void main(String [] args)throws Exception{
  System.out.print("请输入皇后的个数:");
  new Queen(8);
 }
}

原创粉丝点击