八皇后是一道非常经典的深度搜索题型!如果对深搜较为熟练的话!这题难度也不是非常高!
所以还是要多练这种题型的题目!
一般做搜索题都可以利用这种模板,下面附上模板!
void dfs()//先定义一个深度搜索的函数dfs ()
{
if(/*找到结束的条件*/)
{
//后续操作
return; //返回值
}
for(//循环遍历所以方向)
{
if()
continue;
//操作
dfs(//继续向下搜索新的坐标);
//回溯
}
}
int main ()
{
//读入数据
dfs();
return 0;
}
新手可以多多利用模板,等到足够熟悉了之后,就能有自己独到的见解到那时候就不用太过于依附模板了!
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
int a[15],b[15],c[30],d[30];
int total;
int n;
int fk()
{
if(total<=2)
{
for(int k=1;k<=n;k++)
cout<<a[k]<<" ";
cout<<endl;
}
total++;
}
void dfs(int i)
{
if(i>n)
{
fk();
return;
}
else
{
for(int x=1;x<=n;x++)
{
if((!b[x])&&(!c[i+x])&&(!d[i-x+n]))
{
a[i]=x;
b[x]=1;
c[x+i]=1;
d[i-x+n]=1;
dfs(i+1);
b[x]=0;
c[x+i]=0;
d[i-x+n]=0;
}
}
}
}
int main()
{
cin>>n;
dfs(1);
cout<<total;
return 0;
}
原文:https://www.cnblogs.com/fanwentao/p/11629114.html