按行搜索
#include <iostream>
using namespace std;
const int N = 20;
int n;
char mat[N][N];
int col[N], dg1[N], dg2[N];
void dfs(int x){
if(x == n){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << mat[i][j];
}
cout << endl;
}
cout << endl;
return;
}
for(int i=0; i<n; i++){
if(col[i] || dg1[i-x+n] || dg2[i+x]) continue;
col[i] = 1;
dg1[i - x + n] = 1;
dg2[i + x] = 1;
mat[x][i] = 'Q';
dfs(x+1);
col[i] = 0;
dg1[i-x+n] = 0;
dg2[i+x] = 0;
mat[x][i] = '.';
}
}
int main(){
cin >> n;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
mat[i][j] = '.';
dfs(0);
return 0;
}
每一个格子搜索
#include <iostream>
using namespace std;
const int N = 20;
int n;
char mat[N][N];
//int col[N], dg1[N], dg2[N];
int row[N], col[N], dg1[N], dg2[N];
void dfs(int x, int s_i, int s_j){
if(s_i >= n){
if(x == n){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << mat[i][j];
}
cout << endl;
}
cout << endl;
}
return;
}
dfs(x, s_i+(s_j+1)/n, (s_j+1)%n);
if(!row[s_i] && !col[s_j] && !dg1[s_j-s_i+n] && !dg2[s_j+s_i]){
row[s_i] = col[s_j] = dg1[s_j-s_i+n] = dg2[s_j+s_i] = 1;
mat[s_i][s_j] = 'Q';
dfs(x+1, s_i+(s_j+1)/n, (s_j+1)%n);
row[s_i] = col[s_j] = dg1[s_j-s_i+n] = dg2[s_j+s_i] = 0;
mat[s_i][s_j] = '.';
}
return;
}
int main(){
cin >> n;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
mat[i][j] = '.';
dfs(0, 0, 0);
return 0;
}