//8 Queen 递归算法
//如果有一个Q 为 chess[i]=j;
//则不安全的地方是 k行  j位置,j+k-i位置,j-k+i位置

class Queen8{

  static final int QueenMax = 8;
  static int oktimes = 0;
  static int chess[] = new int[QueenMax];//每一个Queen的放置位置


  public static void main(String args[]){
    for (int i=0;i<QueenMax;i++)chess[i]=-1;
    placequeen(0);
    System.out.println("\n\n\n八皇后共有"+oktimes+"个解法 made by yifi 2003");
  }


  public static void placequeen(int num){ //num 为现在要放置的行数
    int i=0;
    boolean qsave[] = new boolean[QueenMax];
    for(;i<QueenMax;i++) qsave[i]=true;
   
    //下面先把安全位数组完成
    i=0;//i 是现在要检查的数组值
    while (i<num){
      qsave[chess[i]]=false;
      int k=num-i;
      if ( (chess[i]+k >= 0) && (chess[i]+k < QueenMax) ) qsave[chess[i]+k]=false;
      if ( (chess[i]-k >= 0) && (chess[i]-k < QueenMax) ) qsave[chess[i]-k]=false;
      i++;
    }
    //下面历遍安全位
    for(i=0;i<QueenMax;i++){
      if (qsave[i]==false)continue;
      if (num<QueenMax-1){
        chess[num]=i;
        placequeen(num+1);
      }
      else{ //num is last one
      chess[num]=i;
      oktimes++;
      System.out.println("这是第"+oktimes+"个解法 如下:");
      System.out.println("第n行:  1 2 3 4 5 6 7 8");
     
      for (i=0;i<QueenMax;i++){
       String row="第"+(i+1)+"行:  ";
       if (chess[i]==0);
       else
        for(int j=0;j<chess[i];j++) row+="--";
        row+="++";
        int j = chess[i];
        while(j<QueenMax-1){row+="--";j++;}
       System.out.println(row);
      }
      }
    }
  //历遍完成就停止

 


#include <stdio.h>
#include <stdlib.h>
#define N 8
int column[N+1];
// 同列是否有皇后,1表示有
int rup[2*N+1]; // 右上至左下是否有皇后
int lup[2*N+1]; // 左上至右下是否有皇后
int queen[N+1] = {0};
int num; // 解答编号
void backtrack(int); // 递归求解
int main(void) {    
    int i;   
    num = 0;   
    for(i = 1; i <= N; i++)       
     column[i] = 1;    
    for(i = 1; i <= 2*N; i++)       
     rup[i] = lup[i] = 1;    
    backtrack(1);    
    return 0;
}
void showAnswer() {  
    int x, y;  
    printf("\n解答 %d\n", ++num);  
    for(y = 1; y <= N; y++) {       
     for(x = 1; x <= N; x++) {           
      if(queen[y] == x) {               
       printf(" Q");           
      }           
      else {               
       printf(" .");           
      }       
     }      
     printf("\n");   
    }}
void backtrack(int i) {    
    int j;   
    if(i > N) {        
     showAnswer();   
    }   
    else {        
     for(j = 1; j <= N; j++) {            
      if(column[j] == 1 && rup[i+j] == 1 && lup[i-j+N] == 1) {               
       queen[i] = j;                   // 设定为占用              
       column[j] = rup[i+j] = lup[i-j+N] = 0;               
       backtrack(i+1);                
       column[j] = rup[i+j] = lup[i-j+N] = 1;            
}        
}    
}
}

posted on 2009-09-02 15:25  风叶  阅读(300)  评论(0编辑  收藏  举报