#include<stdio.h>
int n,count;/*全局变量默认为0*/
int no_collision(int a[],int row,int column){/*检查是否冲突*/
for(int i=1;i<=row;i++){
if(a[i]==column){
return 0;
}else if(i+a[i]==row+column){
return 0;
}else if(i-a[i]==row-column){
return 0;
}
}
return 1;
}
void dfs(int a[],int row){/*深度优先遍历*/
if(row==n+1){
count++;
printf("The %dth group of queens are:\t",count);
for(int i=1;i<row;i++){
printf("%d\t",a[i]);
}
printf("\n");
return;
}
for(int column=1;column<=n;column++){
if(no_collision(a,row,column)){
a[row]=column;
dfs(a,row+1);
a[row]=0;
}
}
}
int main(){
int N=12;
int a[N];
for(int i=0;i<N;i++){
a[i]=0;
}
printf("Please input the number of queens\n");
scanf("%d",&n);
dfs(a,1);
printf("The number of queens' groups is %d.",count);
return 0;
}
|