题解
2025-08-08 09:53:46
发布于:广东
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
struct node{
int a[15] = {0}, ct = 0;
bool vis[15] = {0};
};
int n = 8;
bool check(node n){
for(int i = 1; i < n.ct; i++){
if(n.a[i] + i == n.a[n.ct] + n.ct || n.a[i] - i == n.a[n.ct] - n.ct){
return 0;//如果在对角线就不行
}
}
return 1;
}
int bfs(int n){
int ct = 0;
node xxx;
queue <node> q;
q.push(xxx);
while(!q.empty()){
node head = q.front();
q.pop();
if(head.ct == n){
ct++;
if(ct <= 3){
for(int i = 1; i <= n; i++) cout << head.a[i] << ' ';//输出
cout << endl;
}
continue;
}for(int i = 1; i <= n; i++){
if(!head.vis[i]){
node xx = head;
xx.a[++xx.ct] = i;
if(check(xx)){
xx.vis[i] = 1;
q.push(xx);
}
}
}
}return ct;
}
int main(){
cin >> n;
cout << bfs(n);
return 0;
}
这里空空如也
有帮助,赞一个