N皇后问题
题目
N皇后
按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。
n皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位
示例
![]() |
|---|
解题思路
1.利用回溯算法进行暴力求解。
2.判断每个位置放置Q是否合法。
思路流程
- 编写函数,判断每个位置是否满足条件。
- 编写回溯函数,判断解
- 修改代码。
代码
class Solution {
public:
bool isGoodPosition(const vector<vector<int>> chess, int n, int col, int row){
if(col >=n || row >= n) return false;
//判断横是否正常
for(int i = 0; i < n; i++){
if(chess[i][col] == 1 || chess[row][i] == 1) return false;
}
int col1, row1;
col1 = col;
row1 = row;
while(col1 >= 0 && row1 >= 0 ){
if(chess[row1][col1] == 1) return false;
col1--;
row1--;
}
col1 = col;
row1 = row;
while(col1 < n && row1 >= 0 ){
if(chess[row1][col1] == 1) return false;
col1++;
row1--;
}
return true;
}
void backtracing(vector<vector<string>>& result, vector<string>& path, int cnt, int n, vector<vector<int>>& chess){
if(cnt >= n){
result.push_back(path);
return;
}
string str(n, '.');
for(int i = 0; i < n; i++){
if(isGoodPosition(chess, n, i, cnt)){
chess[cnt][i] = 1;
str[i] = 'Q';
path.push_back(str);
backtracing(result, path, cnt+1, n, chess);
chess[cnt][i] = 0;
path.pop_back();
str[i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> path;
vector<vector<int>> chess(n, vector<int>(n, 0));
backtracing(result, path, 0, n, chess);
return result;
}
};


浙公网安备 33010602011771号