0
点赞
收藏
分享

微信扫一扫

n皇后

爱读书的歌者 2022-02-16 阅读 57



  1. /*
  2. 需要注意,判断x,y位置是否有棋子时,x>y 与x<y时情况不一样,需要及时跳出循环。
  3. */



  4. #include<iostream>
  5. #include<cstring>
  6. using namespace std;
  7.     int n;
  8.     int chess[14][14];
  9.     int num=0;
  10.     bool ifco(int x,int y){
  11.         for(int i=0;i<x;i++){
  12.             if(chess[i][y]==1){
  13.                 return false;
  14.             }
  15.         }
  16.         if(x>=y){
  17.             for(int j=0;j<y;j++){
  18.                 if(chess[x-y+j][j]==1){
  19.                     return false;
  20.                 }
  21.             }
  22.             for(int j=y+1;j<n;j++){
  23.                 if(x+y-j<0)break;
  24.                 if(chess[x+y-j][j]==1){
  25.                     return false;
  26.                 }
  27.             }
  28.          }else{
  29.             for(int i=0;i<x;i++){
  30.                 if(chess[i][y-x+i]==1){
  31.                     return false;
  32.                 }
  33.             }
  34.             for(int j=y+1;j<n;j++){
  35.                 if(x+y-j<0)break;
  36.                 if(chess[x+y-j][j]==1){
  37.                     return false;
  38.                 }
  39.             }
  40.         }
  41.         return true;
  42.     }

  43.     bool ifcould(int x,int y){
  44.         int flag=true;
  45.         int ic=false;
  46.         for(int i=0;i<n;i++){
  47.             for(int j=0;j<n;j++){
  48.                 if(i>=x){
  49.                     ic=true;
  50.                     break;
  51.                 }
  52.                 if(j==y&&chess[i][j]==1){
  53.                     ic=true;
  54.                     flag=false;
  55.                     break;
  56.                 }
  57.                 if(x+y==i+j&&chess[i][j]==1){
  58.                     ic=true;
  59.                     flag=false;
  60.                     break;
  61.                 }
  62.                 if(x-y==i-j&&chess[i][j]==1){
  63.                     ic=true;
  64.                     flag=false;
  65.                     break;
  66.                 }

  67.             }
  68.             if(ic)break;
  69.         }    
  70.         return flag;
  71.     }


  72.     void put(int x){
  73.         if(x>=n){
  74.             num++;

  75.             return ;

  76.         }
  77.         for(int i=0;i<n;i++){
  78.             if(ifco(x,i)){
  79.                 chess[x][i]=1;
  80.                 put(x+1);
  81.                 chess[x][i]=0;
  82.             }
  83.         }

  84.     }
  85. int main(){
  86.     cin>>n;
  87.     //n=8;
  88.     memset(chess,0,sizeof(chess));
  89.     put(0);
  90.     cout<<num<<endl;

  91.     return 0;
  92. }


举报

相关推荐

N 皇后问题

n皇后问题

06:N皇后

2*n皇后问题

51. N 皇后

N皇后-Kotlin解法

0 条评论