Description
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路
- 递归方式
- 主要是要判断当前位置是否是合理位置,参考isValid函数
代码
class Solution {
public:
int totalNQueens(int n) {
int res = 0;
if(n == 0) return 0;
vector<string> flag(n, string(n, '.'));
getResult(flag, n, 0, res);
return res;
}
void getResult(vector<string> &flag, int n, int rows, int &res){
if(rows == n){
res++;
return;
}
else{
for(int i = 0; i < n; ++i){
if(isValid(flag, rows, i, n)){
flag[rows][i] = 'Q';
getResult(flag, n, rows + 1, res);
flag[rows][i] = '.';
}
}
}
}
bool isValid(vector<string> &nums, int rows, int cols, int n){
for(int i = 0; i < rows; ++i)
if(nums[i][cols] == 'Q') return false;
for(int i = rows - 1, j = cols - 1; i >= 0 && j >= 0; --i, --j)
if(nums[i][j] == 'Q') return false;
for(int i = rows - 1, j = cols + 1; i >= 0 && j < n; --i, ++j)
if(nums[i][j] == 'Q') return false;
return true;
}
};