N皇后
2025-10-18 10:29:05
发布于:四川
5阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int n;
int a[15];
bool v[15];
bool eaten(int x1, int y1){
for(int i = 1; i <= n; i++){
if(v[i]){
if(y1 == a[i] || x1 - i == y1 - a[i] || x1 + y1 == i + a[i]){
return true;
}
}
}
return false;
}
void dfs(int x){
if(x == n + 1){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(a[i] == j) cout << 'Q';
else cout << '.';
}
cout << endl;
}
cout << endl;
return;
}
for(int i = 1; i <= n; i++){
if(!eaten(x, i)){
a[x] = i;
v[x] = true;
dfs(x + 1);
v[x] = false;
}
}
}
int main(){
cin >> n;
dfs(1);
return 0;
}
这里空空如也







有帮助,赞一个