您的位置:首页 > 产品设计 > UI/UE

LeetCode 52.N-Queens II

2015-03-08 21:39 162 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: