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.."] ]
直接上代码
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
//string s( n, '.' );
vector<string> path(n, string (n, '.'));
vector<vector<string> > res;
create(0, n, path, res);
return res;
}
bool isValid(int v, int s, int n, vector<string> &path){ //第v行的第s列 是否有效
int vv, ss;
for (int i = 0; i < v; i++){
vv = i;
ss = path[vv].find('Q');
if (ss == s)
return false;
if ((v - vv) == (s - ss))
return false;
if ((v - vv) == (ss - s))
return false;
}
return true;
}
void create(int level, int n, vector<string> &path, vector<vector<string> > &res){
if (level == n){
res.push_back(path);
return;
}
for (int i = 0; i < n; i++){
if (isValid(level, i, n, path)){
path[level][i] = 'Q';
create(level + 1, n, path, res);
path[level][i] = '.';
}
}
}
};