赤裸裸版的
#include <cstdio>
#include <iostream>
using namespace std;
const int N=233;
int n,Ans,ans[N];
bool row[N],fdl[N],sdl[N];
//=============233333===============
void print(){
printf("Ans %d:\n",++Ans);
for (int i=1;i<=n;i++)printf("%d ",ans[i]);puts("");
for (int i=1;i<=n;i++){
for (int j=1;j<ans[i];j++)printf(".");
printf("*");
for (int j=ans[i]+1;j<=n;j++)printf(".");
puts("");
}
}
//=======operators of Queen=========
void Qappend(int x,int y){
ans[x]=y;
row[y]=1;
fdl[x-y+n]=1;// first diagonal
sdl[x + y]=1;//second diagonal
}
void Qremove(int x,int y){
row[y]=0;
fdl[x-y+n]=0;// first diagional
sdl[x + y]=0;//second diagional
}
//============Main solve===========
void dfs(int k){
if (k==n+1){print();return;}
for (int i=1;i<=n;i++){
if (row[i]||fdl[k-i+n]||sdl[k+i])continue;
Qappend(k,i);
dfs(k+1);
Qremove(k,i);
}
}
int main(){
for (;scanf("%d",&n)==1;){
Ans=0;
dfs(1);
printf("Total:%d solutions\n",Ans);
}
return 0;
}
带一点点链表优化,,
#include <cstdio>
#include <iostream>
using namespace std;
const int N=233;
int n,fdl[N],sdl[N],ans[N],Ans;
//=========(Not real)=Dancing=Links========
struct node{
int data;
node *next,*last;
node(){int date=0;node *next=NULL;node *last=NULL;}
};
void Toucha(int x,node *head){//tell me how to
node *p=new node;//translate it into English???
p->data=x;
p->next=head->next;
p->last=head;
p->next->last=p;
head->next=p;
}
//=============233333===============
node* init(){
Ans=0;
node *head=new node;
head->next=head;
head->last=head;
for (int i=n;i>=1;i--){Toucha(i,head);}
return head;
}
void print(){
printf("Ans %d:\n",++Ans);
for (int i=1;i<=n;i++){
for (int j=1;j<ans[i];j++)printf(".");
printf("*");
for (int j=ans[i]+1;j<=n;j++)printf(".");
puts("");
}
}
//=======operators of Qreen=========
void Qappend(int x,int y,node *p){
fdl[x-y+n]=1;// first diagonal
sdl[x + y]=1;//second diagonal
ans[x]=y;
p->last->next=p->next;
p->next->last=p->last;
}
void Qremove(int x,int y,node *p){
fdl[x-y+n]=0;// first diagional
sdl[x + y]=0;//second diagional
p->last->next=p;
p->next->last=p;
}
//============Main solve===========
void dfs(int k,node *head){
if (k==n+1){print();return ;}
for (node *p=head->next;p!=NULL&&p!=head;p=p->next){
int x=p->data;
if (fdl[k-x+n]||sdl[k+x])continue;
Qappend(k,x,p);
dfs(k+1,head);
Qremove(k,x,p);
}
}
int main(){
for (;scanf("%d",&n)==1;){
dfs(1,init());
printf("Total:%d solutions\n",Ans);
}
return 0;
}
有功夫再写个DLX版的