题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
分析与解答:
比上一题更简单了
class Solution{
public:
int count;
int totalNQueens(int n){
vector<string> path(n,string(n,'.'));
dfs(0,0,n,path);
return count;
}
void dfs(int row,int col,int n,vector<string> &path){
if(row == n){
count++;
return;
}
for(int j = 0;j != n;++j){
path[row][j] = 'Q';
if(isSafe(path,n,row,j)){
dfs(row+1,0,n,path);
}
path[row][j] = '.';
}
return;
}
bool isSafe(vector<string> &path,int n,int row,int col){
for(int i = 0;i != row;++i){
if(path[i][col] == 'Q'){
return false;
}
}
int i = row - 1, j = col - 1, k = col + 1;
while((i < row&&i >=0) &&(j >= 0 ||k < n)){
if(path[i][j--] == 'Q'|| path[i][k++] == 'Q'){
return false;
}
i--;
}
return true;
}
};