#include<stdio.h>
#include<stdlib.h>
#define N 100
int x[N];
int abs(int a){
    return a > 0 ? a:-a;
}
int place(int k){//x[k] means the column k_th queue placed
    int i=1;
    while(i < k){
        if((x[i]==x[k])|| (abs(x[i]-x[k])==abs(i-k))) return 0;
        i++;
    }
    return 1;
}
void print(int x[],int n){
    int i,j;
    for(i=1;i<=n;i++){
        for(j=1;j<=n;j++)
            if(x[i]==j) printf("Q ");
            else printf("_ ");
        printf("\n");
    }
    printf("\n");
}
void nqueue(int n){//n >= 4
    int k=1,total=0;
    x[k]=0;
    while(k>0){
        x[k]++;
        while(k<=n && !place(k)){
            x[k]++;
        }
        if(x[k]<=n){
            if(k==n){
                print(x,n);
                total++;
            }
            else{
                k++;
                x[k]=0;
            }
        }
        else{//trace back
            k--;
        }
    }
    printf("共有%d种摆法\n",total);
}
int main(){
    int n;
    scanf("%d",&n);
    nqueue(n);
}

图片描述


binta
73 声望5 粉丝

The Magic Words are Squeamish Ossifrage


引用和评论

0 条评论