深搜思路
1 画递归搜索树
搜索顺序
恢复现场
bool 除去不能搜索的范围
2 除去对角线的技巧
y = x +b b = y - x;
y = -x + b b = y +x;
通过截距相同来控制每一条对角线。副对角线相减会出现负值,注意调整一下
#include<bits/stdc++.h>
using namespace std;
int n;
int path[15];
bool col[15] , dg[30] ,udg[30] ;
int ans = 0;
void dfs (int x )
{
if (x > n)
{
ans ++;
if ( ans <= 3)
{
for (int i = 1 ; i <= n ; i ++)
cout<<path[i]<<" ";
cout<<endl;
}
return ;
}
for (int j = 1 ; j <= n ; j ++)
{
if (!col[j] && !dg[j + x] && !udg[x - j + n])
{
path[x] = j;
col[j] = dg[j + x] = udg[x - j + n] = true;
dfs(x + 1);
col[j] = dg[j + x] = udg[x - j + n] = false;
path[x] = 0;
}
}
}
int main()
{
cin>>n;
dfs(1);
cout<<ans;
return 0;
}
代码细节