The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
著名的n皇后问题,要求记录摆放位置,下面几行是关键:
void dfs(int level){
if(level==N){
output();
}
else{
for(int i=0;i<N;i++){
if(check(level+1,i+1)){
m[level][i]=1;
dfs(level+1);
m[level][i]=0;
}
}
}
}
vector<vector<int> > m是全局变量,用来记录遍历轨迹,遍历前设上值,遍历后去掉。每一次调到output的时候,所有压入栈中的函数返回,都会调到
m[level][i]=0;此时m清零。
<pre name="code" class="cpp">int N;
vector<vector<int> > m;
vector<vector<string> > result;
bool check(int row,int column){
if(row==1) return true;
int i,j;
for(i=0;i<=row-2;i++){
if(m[i][column-1]==1) return false;
}
i = row-2;
j = i-(row-column);
while(i>=0&&j>=0){
if(m[i][j]==1) return false;
i--;
j--;
}
i = row-2;
j = row+column-i-2;
while(i>=0&&j<=N-1){
if(m[i][j]==1) return false;
i--;
j++;
}
return true;
}
void output()
{
vector<string> vec;
for(int i=0;i<N;i++){
string s;
for(int j=0;j<N;j++){
if(m[i][j]==1)
s.push_back('Q');
else
s.push_back('.');
}
vec.push_back(s);
}
result.push_back(vec);
}
void dfs(int level){
if(level==N){
output();
}
else{
for(int i=0;i<N;i++){
if(check(level+1,i+1)){
m[level][i]=1;
dfs(level+1);
m[level][i]=0;
}
}
}
}
vector<vector<string> > solveNQueens(int n) {
N=n;
for(int i=0;i<n;i++){
vector<int> a(n,0);
m.push_back(a);
}
dfs(0);
return result;
}