- N-Queens Add to List QuestionEditorial Solution My Submissions
Total Accepted: 67411
Total Submissions: 235847
Difficulty: Hard
Contributors: Admin
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
回溯算法:
八皇后问题是回溯算法的经典应用之一。回溯算法应用于一些没有明显确定的计算规则的问题有很好的效果。实际上回溯算法就是一种优化的穷举算法,只不过应用穷举算法时,将一些不可能的分支情况排除,然后回溯到之前的岔路口,类似于DFS算法。
下面给出了N皇后问题的回溯算法解答,备注给出了详细解释。
class Solution {
bool canBePlaced(const vector<string> &tmp,int row,int col,int n){//由于我们是按行从上到下放置Queen,所以我们无需考虑同一行以及该位置之后行
for(int i = row - 1;i >=0;--i){
if(col - (row - i) >= 0 && tmp[i][col - (row - i)] == 'Q')//主对角线是否有Queen
return false;
if(col + (row - i) < n && tmp[i][col + (row - i)] == 'Q')//次对角线是否有Queen
return false;
if(tmp[i][col] == 'Q')//同一列是否有Queen
return false;
}
return true;
}
void __SolveNQueens(vector<vector<string>> &res,vector<string> &tmp,int row,int n){
for(int col = 0;col != n;++col){
if(canBePlaced(tmp,row,col,n)){
if(row == n - 1){
tmp[row][col] = 'Q';
res.push_back(tmp);
tmp[row][col] = '.';
return;
}
tmp[row][col] = 'Q';
__SolveNQueens(res,tmp,row + 1,n);
tmp[row][col] = '.';
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> tmp(n,string(n,'.'));
__SolveNQueens(res,tmp,0,n);
return res;
}
};