- 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;
}
};