C语言解决8皇后问题
#include<iostream> using std::cout; using std::endl; #define my_abs(x) ((x)>=0?(x):(-(x))) const int n=8; void output(int a[],int n) { static int count=1; cout<<"this is the "<<count<<"th answer"<<endl<<endl; for (int i=1;i<=n;i++) cout<<i<<" "<<a[i]<<endl; count++; } bool constraint(int a[],int k) { for(int i=1;i<k;i++) if(my_abs(k-i)==my_abs(a[k]-a[i])||(a[i]==a[k])) return false; return true; } void back_track(int a[],int i) { if(i>n) { output(a,n); } else { for(int j=1;j<=n;j++) { a[i]=j; if(constraint(a,i)) back_track(a,i+1); } } } int main() { int *a=new int[n+1]; back_track(a,1); delete []a; return 0; }