N-Queens
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) {
dfs_2(0,n);
return b;
}
int num;
int v[3][100];
vector<string>a;
int c[100];
vector<vector<string>>b;
int dfs_2(int cur,int n) // 填充第cur行
{
if(cur==n){
a.clear();
for(int i=0;i<n;i++){ // vector<string>a; a 为每一种方案
string s(n,'.'); //首先赋初值
s[c[i]]='Q'; // 将每一行的queen的位置用Q表示
a.push_back(s); // 加入到a中
}
b.push_back(a); // 将每一种可能加入b中
}
else{
for(int i=0;i<n;i++){// 列
if(!v[0][i]&&!v[1][cur-i+n]&&!v[2][cur+i]){
v[0][i]=v[1][cur-i+n]=v[2][cur+i]=1;
c[cur]=i;
dfs_2(cur+1,n);
v[0][i]=v[1][cur-i+n]=v[2][cur+i]=0;
}
}
}
}
};