八皇后问题
2023-08-07 13:56:11
发布于:浙江
#include<bits/stdc++.h>
using namespace std;
int cnt,a[10],b[10],c[20],d[20];
void f(int x) {
if(x > 8) {
cnt++;
cout<<"No. "<<cnt<<endl;
for(int i = 1; i <= 8; i++) {
for(int j = 1; j <= 8; j++) {
if(a[i] == j) cout<<1<<" ";
else cout<<0<<" ";
}
cout<<endl;
}
return;
}
for(int i = 1; i <= 8; i++) {
if(!b[i] && !c[x - i + 8] && !d[x + i]) {
a[x] = i;
b[i] = 1;
c[x - i + 8] = 1;
d[x + i] = 1;
f(x + 1);
b[i] = 0;
c[x - i + 8] = 0;
d[x + i] = 0;
}
}
}
int main() {
f(1);
return 0;
}
这里空空如也
有帮助,赞一个