class Solution {
public:
int arr[10];
int res=0;
int N;
bool isSafe(int row,int col)
{
for (int k = 0; k < row; k++) //遍历放置了皇后的行
{
if (arr[k] == col) return 0; //同一列
if (row - k == col - arr[k]) return 0; //从左上至右下,行之差和列之差相等
if ((row - k) + (col - arr[k]) == 0) return 0;//从左下至右上,行之差列之差和为0
}
return 1;
}
void Backtrack(int st,bool flag)
{
if(st==N&&flag)
{
res++;
return;
}
for(int i=0;i<N;i++)
{
flag=isSafe(st,i);
if(flag)
{
arr[st]=i;
Backtrack(st+1,flag);
arr[st] = -1;
}
else
continue;
}
}
int totalNQueens(int n) {
N=n;
Backtrack(0,false);
return res;
}
};