题目描述
继续思考“n-queens”问题 这次我们不是输出皇后的排列情况,而是输出n皇后问题一共有多少种解法
正解
class Solution {
public:
/**
*
* @param n int整型
* @return int整型
*/
int totalNQueens(int n) {
// write code here
int res = 0;
// ???
vector<string> chessboard(n,string(n, '0'));
dfs(chessboard, n, 0, res);
return res;
}
void dfs(vector<string> &chessboard, int size, int row, int &result){
if(row == size){
result++;
return ;
}
for(int col = 0; col < size; col++){
if(isvalid(chessboard, size, row, col)){
chessboard[row][col] = '1';
dfs(chessboard, size, row+1, result);
chessboard[row][col] = '0';
}
}
}
bool isvalid(vector<string> &chessboard, int size,int row, int col){
// 检查列和对角线
for(int i = row - 1; i >= 0; i--){
if(chessboard[i][col] == '1')
return false;
}
for(int i = row - 1, j = col - 1; i >= 0 && j >= 0 ; i--, j--){
if(chessboard[i][j] == '1')
return false;
}
for(int i = row - 1, j = col + 1; i >= 0 && col < size; i--, j++){
if(chessboard[i][j] == '1')
return false;
}
return true;
}
};
错解
class Solution {
public:
/**
*
* @param n int整型
* @return int整型
*/
int totalNQueens(int n) {
// write code here
int res = 0;
vector<vector<int>> chessboard(n,vector<int>(n, 0));
dfs(chessboard, n, 0, res);
return res;
}
void dfs(vector<vector<int>> &chessboard, int size, int row, int &result){
if(row == size){
result++;
return ;
}
for(int col = 0; col < size; col++){
if(isvalid(chessboard, size, row, col)){
chessboard[row][col] = 1;
dfs(chessboard, size, row+1, result);
chessboard[row][col] = 0;
}
}
}
bool isvalid(vector<vector<int>> &chessboard, int size,int row, int col){
// 检查列和对角线
for(int i = row - 1; i >= 0; i--){
if(chessboard[i][col] == 1)
return false;
}
for(int i = row - 1, j = col - 1; i >= 0 && j >= 0 ; i--, j--){
if(chessboard[i][j] == 1)
return false;
}
for(int i = row - 1, j = col + 1; i >= 0 && col < size; i--, j++){
if(chessboard[i][j] == 1)
return false;
}
return true;
}
};
错因分析
- 知道是初始化的时候出的的问题,不太清楚为什么用string、char就没问题,用int就出了问题。
- 对于vector的用法不是很清楚。