题目:
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:
bool isValid(int n, int i, int j, vector<int>& record, vector<string>& cur) {
if(record[j])
return false;
for(int ii = i, jj = j; ii >= 0 && jj >= 0; ii--, jj--)
if(cur[ii][jj] == 'Q')
return false;
for(int ii = i, jj = j; ii >= 0 && jj < n; ii--, jj++)
if(cur[ii][jj] == 'Q')
return false;
return true;
}
void backSolver(int rest_n, int n, vector<string> cur, vector<int> record, vector<vector<string>>& res) {
if(rest_n == n)
{
res.push_back(cur);
return;
}
for(int i = 0; i<n; i++)
{
if(isValid(n, rest_n, i, record, cur))
{
cur[rest_n][i] = 'Q';
record[i] = 1;
backSolver(rest_n + 1, n, cur, record, res);
cur[rest_n][i] = '.';
record[i] = 0;
}
}
return;
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> cur;
string cur_line = "";
for(int i = 0; i<n; i++)
cur_line += ".";
for(int i = 0; i<n; i++)
cur.push_back(cur_line);
vector<int> record(n+1, 0);
backSolver(0, n, cur, record, res);
return res;
}
};