在牛客上刷到N皇后问题。使用用回溯法,然后直接想到的就是下面的,但是没有通过测试(1<=n<=14),n=14时就超时了。
//n=14超时
void dfs(int dept,int n,vector<int>& pos,int &res)
{
if(dept>n)
{
res++;
return ;
}
int mark=1;//标记是否可以继续递归
for(int i=1;i<=n;i++)
{
mark=1;
pos[dept]=i;//第dept个放在第i列
for(int j=1;j<dept;j++)
{
//同一列 或者 在同一对角线(x1-x2)==(y1-y2)
if(i==pos[j] || abs(dept-j)==abs(i-pos[j]) )