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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
[Solution]
class Solution {
public:
// is the new Queen valid
bool valid(int row, int column, vector<pair<int, int> > &located){
for(int i = 0; i < located.size(); ++i){
if(located[i].first + located[i].second == row + column || located[i].second - located[i].first == column - row){
return false;
}
}
return true;
}
// search location
vector<vector<string> > search(bool column[], int n, int mth, vector<pair<int, int> > &located){
vector<vector<string> > res;
// the last row
if(mth == n - 1){
for(int i = 0; i < n; ++i){
if(column[i] == false && valid(mth, i, located)){
string str(n, '.');
str[i] = 'Q';
// add result
vector<string> tmp;
tmp.push_back(str);
res.push_back(tmp);
}
}
}
else{
for(int i = 0; i < n; ++i){
// valid in the ith column
if(column[i] == false && valid(mth, i, located)){
// locate a Queen in (mth, i)
column[i] = true;
located.push_back(make_pair(mth, i));
string str(n, '.');
str[i] = 'Q';
// search in the next row
vector<vector<string> > r = search(column, n, mth+1, located);
for(int j = 0; j < r.size(); ++j){
r[j].insert(r[j].begin(), str);
res.push_back(r[j]);
}
// back
column[i] = false;
located.pop_back();
}
}
}
return res;
}
// n queen
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// the columns with Queen
bool column[n];
memset(column, false, sizeof(column));
// located Queens
vector<pair<int, int> > located;
// search
return search(column, n, 0, located);
}
};
说明:版权所有,转载请注明出处。 Coder007的博客