05
一、回溯(DFS)
直接上代码:(八皇后(节选))
bool check(int x,int y){
if(h[x]==0 && l[y]==0 && z[x+y]==0 && f[x-y+n]==0) return 1;
return 0;
}
void dfs(int x){
if(x==n+1){
cnt++;
if(cnt<=3){
for(int i=1;i<=n;i++){
cout<<a[i]<<' ';
}cout<<endl;
}
return ;
}
for(int i=1;i<=n;i++){
if(check(x,i)){
a[x]=i;
h[x]++;
l[i]++;
z[x+i]++;
f[x-i+n]++;
dfs(x+1);
h[x]--;
l[i]--;
z[x+i]--;
f[x-i+n]--;
}
}
}
小学生,自用勿喷