-
问题介绍
- 问题描述: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.
- 示例:

- 约束条件:NULL
-
解决思路
- 思路:
- 经典的”八皇后“问题,采用回溯法,用递归算法解决该问题;
- 从第一行开始,对每一行进行皇后位置的摆放,每次摆放完皇后的位置后,需要对刚摆放的位置进行合法性检查,即保证已经存在的皇后与刚加入的皇后不会存在冲突;如果检查合法性为true则判断如果当前行为最后一行则将当前的所有皇后的摆放位置加入结果resp中,否则进入下一行皇后的摆放;如果检查合法性为false,则将当前位置还原为字符’.’,对下一列位置进行摆放尝试;如果所有位置都尝试且失败,则回溯到上一行的皇后摆放中;因为此题需要求解所有满足条件的皇后摆放方法,所以处理函数不进行返回,即对于每一行都尝试所有列位置的摆放,当当前行的所有位置都尝试过了后,就会进行回溯,这样就能将所有满足条件的解法都找到;
- 对于皇后位置合法性检查函数,因为按照行数进行皇后的摆放,所以不存在行冲突,检查当前摆放皇后和所有之前存在皇后的列数是否存在冲突,也检查对角线的规则(abs(col-i_col)==(row-i)),即当前皇后位置[row,col]与之前皇后[i,i_col]列数数相减的绝对值是否等于行数相减的值;
- 代码
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> resp;
vector<string> Q(n,string(n,'.'));
int row=0;
Proc(resp,Q,row,n);
return resp;
}
void Proc(vector<vector<string>>& resp,vector<string>& Q,int row,int n)
{
for(int i=0;i<n;i++)
{
Q[row][i]='Q';
if(check(Q,row,i))
{
if(row==n-1)
{
resp.push_back(Q);
}
else
{
Proc(resp,Q,row+1,n);
}
}
Q[row][i]='.';
}
}
bool check(vector<string>& Q,int row,int col)
{
for(int i=0;i<row;i++)
{
int i_col=0;
for(int j=0;j<Q[i].length();j++)
{
if(Q[i][j]=='Q')
i_col=j;
}
if(col==i_col||(abs(col-i_col)==(row-i)))
return false;
}
return true;
}
};