鲍鱼开始讲八皇后了

Posted by Cww97 on 2016-03-24

版权声明:本文为博主原创文章,未经博主允许不得转载。原文所在http://blog.csdn.net/cww97 https://blog.csdn.net/cww97/article/details/50968131
赤裸裸版的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#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;
}

带一点点链表优化,,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#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版的

这里写图片描述
这里写图片描述