n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
基础题复习一下,回溯算法
#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
vector<vector<string>> res;
bool QueenIsLegal(int row, int column,int n,vector<string>& chessboard){
int x = row;
int y = column;
while(x>=0 && y>=0){
if(chessboard[x][y]=='Q')
return false;
x--;
y--;
}
x = row;
y = column;
while(x>=0){
if(chessboard[x][y]=='Q')
return false;
x--;
}
x = row;
y = column;
while(x>=0 && y<n){
if(chessboard[x][y]=='Q')
return false;
x--;
y++;
}
return true;
}
void backtrace(int row,vector<string> &chessboard,int n){
if(row==n){
res.push_back(chessboard);
return;
}
for(int i=0;i<n;i++){
if(QueenIsLegal(row,i,n,chessboard)){
chessboard[row][i] = 'Q';
backtrace(row+1,chessboard,n);
chessboard[row][i]='.';
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
string rows;
for(int i=0;i<n;i++){
rows+='.';
}
vector<string> temp(n,rows);
backtrace(0,temp,n);
return res;
}
};
int main(){
Solution *ps = new Solution();
vector<vector<string>> res = ps->solveNQueens(8);
cout<<"res:"<<res.size()<<endl;
return 0;
}