C++实现八皇后问题
#include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; #include <cmath> //非递归算法解决八皇后问题。求出可能的92种。 // using std::abs; int main() { static int queen[9]; static int count=1; for (int A=1;A<=8;A++) { for (int B=1;B<=8;B++) { if (B==A) { continue; } queen[2]=B; if ((abs(B-A))==1) { continue; } queen[1]=A; for (int C=1;C<=8;C++) { if ((C==B) || (C==A)) { continue; } if ((abs(C-B)==1)||(abs(C-A)==2)) { continue; } queen[3]=C; for (int D=1;D<=8;D++) { if ((D==C)||(D==B)||(D==A)) { continue; } if ((abs(D-C)==1)||(abs(D-B)==2)||(abs(D-A)==3)) { continue; } queen[4]=D; for (int E=1;E<=8;E++) { if ((E==D)||(E==C)||(E==B)||(E==A)) { continue; } if ((abs(E-D)==1)||(abs(E-C)==2)||(abs(E-B)==3)||(abs(E-A)==4)) { continue; } queen[5]=E; for (int F=1;F<=8;F++) { if ((F==E)||(F==D)||(F==C)||(F==B)||(F==A)) { continue; } if ((abs(F-E)==1)||(abs(F-D)==2)||(abs(F-C)==3)||(abs(F-B)==4)||(abs(F-A)==5)) { continue; } queen[6]=F; for (int G=1;G<=8;G++) { if ((G==F)||(G==E)||(G==D)||(G==C)||(G==B)||(G==A)) { continue; } if ((abs(G-F)==1)||(abs(G-E)==2)||(abs(G-D)==3)||(abs(G-C)==4)||(abs(G-B)==5)||(abs(G-A)==6)) { continue; } queen[7]=G; for (int I=1;I<=8;I++) { if ((I==G)||(I==F)||(I==E)||(I==D)||(I==C)||(I==B)||(I==A)) { continue; } if ((abs(I-G)==1)||(abs(I-F)==2)||(abs(I-E)==3)||(abs(I-D)==4)||(abs(I-C)==5) ||(abs(I-B)==6)||(abs(I-A)==7)) { continue; } queen[8]=I; cout<<" NO."<<setw(2)<<count<<": "; for (int i=1;i<=8;i++) { cout<<setw(3)<<queen[i]; } count++; cout<<endl; } } } } } } } } return 0; }
#include <iostream> using namespace std; //递归算法解决八皇后问题。总共有92种解法。 int c[20], n=8, cnt=0; void print(){ for(int i=0; i<n; ++i){ for(int j=0; j<n; ++j){ if(j == c[i]) cout<<"1 "; else cout<<"0 "; } cout<<endl; } cout<<endl; } void search(int r){ if(r == n){ print(); ++cnt; return; } for(int i=0; i<n; ++i){ c[r] = i; int ok = 1; for(int j=0; j<r; ++j) if(c[r]==c[j] || r-j==c[r]-c[j] || r-j==c[j]-c[r]){ ok = 0; break; } if(ok) search(r+1); } } int main(){ search(0); cout<<cnt<<endl; return 0; }