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>> solutions;
vector<int> queue(n, -1);
recursiveFun(solutions, queue, n, 0);
return solutions;
}
void recursiveFun(vector<vector<string>> &solutions, vector<int> &queue, int n, int row)
{
if (row >= n)
{
vector<string> ret = getResult(queue);
solutions.push_back(ret);
}
else
{
for (int j = 0; j < n; ++j)
{
if (isValid(queue, row, j))
{
queue[row] = j;
recursiveFun(solutions, queue, n, row + 1);
}
}
}
}
bool isValid(vector<int> queue, int r, int c)
{
if (queue.empty())
return true;
for (int i = 0; i < r; ++i)
{
if (queue[i] == c || abs(i - r) == abs(queue[i] - c))
return false;
}
return true;
}
vector<string> getResult(vector<int> queue)
{
if (queue.empty())
{
return vector<string>();
}
int len = queue.size();
vector<string> ret(len, string(len,'.'));
for (int i = 0; i < len; ++i)
{
ret[i][queue[i]] = 'Q';
}
return ret;
}
};