源码:
#include<bits/stdc++.h>
using namespace std;
int n, a[15][15], cnt;
int dx[] = {0, -1, 0, 1},
dy[] = {1, 0, -1, 0};
void print(){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(a[i][j] == 1){
cout << j << " ";
}
}
}
cout << endl;
}
bool check(int n, int x, int y){
//检查列
for(int i = 1; i <= n; i++){
if(a[i][y] == 1) return false;
}
//检查左上-右下
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(i - j == x - y){
if(a[i][j] == 1) return false;
}
}
}
//检查右上-左下
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(i + j == x + y){
if(a[i][j] == 1) return false;
}
}
}
return true;
}
void dfs(int n, int r){
if(r == n + 1){
cnt++;
if(cnt <= 3){
print();
}
return;
}
for(int i = 1; i <= n; i++){
if(check(n, r, i)){
a[r][i] = 1;
dfs(n, r + 1);
a[r][i] = 0;
}
}
}
int main(){
cin >> n;
dfs(n, 1);
cout << cnt << endl;
return 0;
}