#include "stdio.h" const int N=16;// 在这里设置N值 int Validate(int row,int col,int ExistsTbl[]) { int i; for(i=0;i<col;i++) { if(row==ExistsTbl[i])//是否同行 { return 0; } else if(row-col==ExistsTbl[i]-i||row+col==ExistsTbl[i]+i)//对角线 return 0; } return 1; } int place_queue(int col,int ExistsTbl[]) { int row=0,flag=0; if(col==N) { flag=1; } else { while(row<N&&flag==0) { if(Validate(row,col,ExistsTbl)) { ExistsTbl[col]=row; flag=place_queue(col+1,ExistsTbl); } else row++; if(flag==0)//回朔 row++; } } return flag; } void main() { int ExistsTbl[100],i,j; if(place_queue(0,ExistsTbl)==1) { printf(" "); for(i=1;i<=N;i++) { printf("%3d",i); } printf("/n"); for(i=1;i<=N;i++) { printf("%d",i); for(j=0;j<N;j++) if(ExistsTbl[j]==i-1) printf("%3c",'Q'); else printf("%3c",'*'); printf("/n"); } } }
参考文献
http://www.cnblogs.com/jillzhang/archive/2007/10/21/922830.html