#include<stdio.h>
#include<stdlib.h>
#include<math.h>const int MAX=32767;const int N=4;voiddisplay(int c[N+1]){
int i,j;printf("\n");for(i=1;i<=N;i++){for(j=1;j<=N;j++){if(c[i]==j)printf("%3d",1);elseprintf("%3d",0);}printf("\n");}printf("\n");}
bool solution(int c[N+1],int k)//单点计算{
int i,j;for(i=1;i<=k;i++)//是否同列for(j=i+1;j<=k;j++)if(c[i]==c[j])returnfalse;for(i=1;i<=k;i++)//是否同一对角线for(j=i+1;j<=k;j++)if(j-i==abs(c[i]-c[j]))//斜率为1(-1)returnfalse;returntrue;}
int advanced(int c[N+1],int k){
int col;for(col=1;col<=N;col++)//最多只有4列{
c[k]=col;if(solution(c,k))//部分解或解{if(k==4)//解display(c);else//部分解 advanced(c,k+1);//移至下一行}}
c[k]=0;//返回前清0(回溯)return0;}
int queens(){
int c[N+1]={0,};advanced(c,1);return0;}
int queens_iteration(){
int col,k;
int c[N+1]={0,};
k=1;while(k>=1){while(k<=4){
c[k]++;if(solution(c,k))//合法点{if(k!=4)
k++;//移至下一行elsedisplay(c);//部分解或解}elseif( c[k]==4)break;}
c[k]=0;//返回前清0(回溯)
k--;while( c[k]==4){
c[k]=0;//返回前清0(回溯)
k--;}}return0;}
int main(){printf("递归:\n");queens();printf("\n迭代:\n");queens_iteration();printf("\n");return0;}