非常经典的一道题目,一看到就能立刻想到用搜索解决,但是这一道题目的输出,有一个特殊的要求,即“按字典序输出前三个解”。如果我们用搜索,得到所有的解,再进行排序,不免过于繁琐,因此我们就想到可以从数字的角度解决这个问题
因此,我们可以建立一个一维数组,以此来表示每一个皇后被放置的位置,如 就表示第 个皇后被放在第 行,第 列 得到了每个皇后的位置,我们也就可以判断出当前情况是否满足题意
条件1: 每行、每列有且只有一个
比较容易实现,因为我们使用一维数组来标记,所以每行只会出现一次标记,所以只要保证 中每一个 都不同即可,我们可以用全排列来实现
void dfs(int depth)
{
if(depth>n)
{
if(check())
{
for(int i=1;i<depth;i++) cout<<a[i]<<" ";
cout<<endl;
}
}
else
{
for(int i=1;i<=n;i++)
{
if(book[i]==0)//如果这个数没有被用过
{
a[depth]=i;//加入全排列
book[i]=1;//标记为用过
dfs(depth+1);//继续搜索下一层
book[i]=0;//回溯,标记为未用过
}
}
}条件2:每条对角线上至多有一个棋子
需要我们经过一定的判断,我们假使两个皇后在同一对角线上,那么他们所在的“行”之间的距离,肯定等于他们“列”之间的距离,所以我们可以得到如下判断公式
代码:
int check()
{
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
if(abs(i-j)==abs(a[i]-a[j]))
return 0;
return 1;
}最后就得到如下代码:
#include "bits/stdc++.h"
using namespace std;
int queen[15],book[15],n,ans;
int check(int n)
{
for(int i=1;i<=n-1;i++)//将这个数和前面的做判断,看是否在同一对角线
if(abs(queen[i]-queen[n])==abs(i-n))
return 0;
return 1;
}
int fun(int depth)
{
if(depth>n)
{
ans++;
if(ans<=3)
{
for(int i=1;i<depth;i++)
cout<<queen[i]<<" ";
cout<<endl;
}
}
else
{
for(int i=1;i<=n;i++)
{
if(book[i]==0)
{
book[i]=1;
queen[depth]=i;
if(check(depth)) fun(depth+1);//每次新添加一个数,就做判断,如果满足,再搜索下一层
book[i]=0;
}
}
}
}
int main()
{
cin>>n;
fun(1);
cout<<ans<<endl;
return 0;
}要注意的是,在上面这段代码中,其实已经进行了一个优化,即将判断是否可行的这个 函数放在全排列过程中,实时判断,每次全排列一个数,就将这个数与之前的所有数进行比较,判断是否在对角线上,如果不在,才继续往下一层搜索。
这种优化方式,可以去除掉很多无意义的全排列,减低了时间复杂度
PS:顺便附上某人做这道题的高级方法
#include<bits/stdc++.h>
using namespace std;
int a;
int main()
{
cin>>a;
if(a==6){
cout<<"2 4 6 1 3 5\n"<<"3 6 2 5 1 4\n"<<"4 1 5 2 6 3\n"<<"4";
}else if(a==7){
cout<<"1 3 5 7 2 4 6\n"<<"1 4 7 3 6 2 5\n"<<"1 5 2 6 3 7 4\n"<<"40"<<endl;
}else if(a==8){
cout<<"1 5 8 6 3 7 2 4\n"<<"1 6 8 3 7 4 2 5\n"<<"1 7 4 6 8 2 5 3\n"<<"92"<<endl;
}else if(a==9){
cout<<"1 3 6 8 2 4 9 7 5\n"<<"1 3 7 2 8 5 9 4 6\n"<<"1 3 8 6 9 2 5 7 4\n"<<"352"<<endl;
}else if(a==10){
cout<<"1 3 6 8 10 5 9 2 4 7\n"<<"1 3 6 9 7 10 4 2 5 8\n"<<"1 3 6 9 7 10 4 2 8 5\n"<<"724"<<endl;
}else if(a==11){
cout<<"1 3 5 7 9 11 2 4 6 8 10\n"<<"1 3 6 9 2 8 11 4 7 5 10\n"<<"1 3 7 9 4 2 10 6 11 5 8\n"<<"2680"<<endl;
}else if(a==12){
cout<<"1 3 5 8 10 12 6 11 2 7 9 4\n"<<"1 3 5 10 8 11 2 12 6 9 7 4\n"<<"1 3 5 10 8 11 2 12 7 9 4 6\n"<<"14200"<<endl;
}else if(a==13){
cout<<"1 3 5 2 9 12 10 13 4 6 8 11 7\n"<<"1 3 5 7 9 11 13 2 4 6 8 10 12\n"<<"1 3 5 7 12 10 13 6 4 2 8 11 9\n"<<"73712"<<endl;
}
return 0;
}