52. N皇后 II
题目描述
Follow up for N-Queens problem.Now, instead outputting board configurations,return the total number of distinct solutions.
代码实现
class Solution {
public:
int totalNQueens(int n)
{
int sum = 0;
//如果用二维数组表示棋盘的话,用vector<vector<bool>>
//一维数组表示棋盘,下标代表行,存储的元素代表此行(对应于这个下标行)
//放置皇后的列的下标
vector<int> temp;
for(int i = 0;i < n;i++)
temp.push_back(i);
totalNQueensCore(0,temp,sum);
return sum;
}
bool isValid(vector<int> &temp, int row)
{
for(int i = 0; i < row;i++)
{ //由于我们这里的棋盘放置已经保证了放置的皇后不同行,不同列,所以这里只检验
if(abs(row-i) == abs(temp[row]-temp[i]))//是否在同一正反斜线上
return false;
}
return true;
}
void totalNQueensCore(int row,vector<int> &temp,int &sum)
{
if(row == temp.size())
{
sum++;
return;
}
//这里temp里的元素存储每一行列里能放置的所有可能的信息,前面行的列里已经放置过的元素
//在后面的行的列里不能再放置,这种处理方式很自然的保证了N皇后不会放置在同一列
//也就是说,现在主要做的是遍历列号的一个permutation,保证正反斜线不冲突
for(int index = row; index < temp.size();index++)//枚举这一行的所有可能的摆法
{
swap(temp[row],temp[index]);
if(isValid(temp,row))
totalNQueensCore(row + 1,temp,sum);
swap(temp[row],temp[index]);
}
}
};