题目描述:
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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<int> pos(n,-1);
NQueens(result,pos,0);
return result;
}
// row表示当前行,pos存储之前所有行的皇后所在的列数
void NQueens(vector<vector<string>>& result, vector<int> pos, int row)
{
int n=pos.size();
for(int i=0;i<n;i++)
{
pos[row]=i; // 对于当前行,尝试所有可能的列数
bool isValid=true;
for(int j=0;j<row;j++)
{
if(pos[row]==pos[j]||pos[row]-pos[j]==row-j||pos[row]-pos[j]==j-row)
{
isValid=false;
break;
}
}
if(isValid)
{
if(row==n-1)
{
vector<string> v;
for(int j=0;j<n;j++)
{
string temp(n,'.');
temp[pos[j]]='Q';
v.push_back(temp);
}
result.push_back(v);
}
else NQueens(result,pos,row+1);
}
}
}
};
本文详细解析了N皇后问题的算法实现,通过回溯法在N×N的棋盘上放置N个皇后,使得任意两个皇后都不会互相攻击。示例代码展示了如何返回所有可能的解决方案配置。

被折叠的 条评论
为什么被折叠?



