#include<stdio.h> #include<stdlib.h> #include<math.h> #define N 4 int isplace(int pos[],int k) { int j; for(j=1;j<k;++j) if((pos[j]==pos[k])||fabs(j-k)==fabs(pos[j]-pos[k])) { return 0; } return 1; } int main() { int i,j, int pos[N+1]; int count =1 ; for(i=0;i<N;++i) pos[i]=0; j = 1; while(j>=1) { pos[j] = pos[j]+1; /*尝试摆放第i个皇后*/ while(pos[j]<=N&&(isplace(pos,j)==0)) { pos[j] = pos[j]+1; } /*得到一个摆放方案*/ if(pos[j]<=N&&j==N) { printf("方案%d: ",count++); for(i=1;i<=N;++i) { printf("%d ",pos[i]); } printf(" "); } /*考虑下一个皇后*/ if(pos[i]<=N&&j<N) { j=j+1; } else {/*返回考虑上一个皇后。*/ pos[j] = 0; j = j- 1; } } return 0; }