- #ifdef EIGHT_EMPRESS
- //8皇后算法:
- /*
- *判断是否同列冲突,是否对线冲突
- */
- FILE *fp;
- int Empress_Judge(int pos,int *a,int dDimension)
- {
- int i;
- int step;
- if(pos>=dDimension || pos<0)
- return -1;
- for(i=0;i<pos;i++){
- if(a[i]==a[pos])
- return -1;
- }
- i=pos-1;
- step=1;
- while(i>=0 && a[pos]-step>=0){
- if(a[i]==a[pos]-step)
- return -1;
- i--;
- step++;
- }
- i=pos-1;
- step=1;
- while(i>=0 && a[pos]+step <= dDimension-1){
- if(a[i]==a[pos]+step)
- return -1;
- i--;
- step++;
- }
- return 0;
- }
- /*
- *打印当前皇后解法
- */
- void empress_printf(int dCount,int *a,int dDimension)
- {
- fprintf(fp,"dcount=%2d \\r\\n",dCount);
- int i;
- for(i=0;i<dDimension;i++){
- fprintf(fp,"%d ",a[i]);
- }
- //printf("\\n");
- fprintf(fp,"\\r\\n---------\\r\\n");
- }
- /*
- *在一个N*N的棋盘上放置N个皇后,每行一个并使其不能互相攻击(同一行、同一列、同一斜线上的皇后都会自动攻击)
- *假设N取值0~N-1
- */
- int eight_empress_algorith(int dDimension)
- {
- int dRet = -1;//返回值
- int dCount = 0;
- int k=0; //k= 0,1...dDimension
- int j=0; //H 行位置
- int i=0; //V 列位置
- int* a = NULL;//a[i]=j表示第i列的第j行存在empress
- a = (int *)malloc(sizeof(int)*dDimension);
- if(a == NULL)
- return dCount;
- else
- memset(a, 0x0, sizeof(int)*dDimension);
- if((fp=fopen("b.txt","w"))==NULL){
- trace_printf("open file error !\\n");
- }
- j=0;//默认首元
- a[i++]=j;//默认第一个元素为a[0]=0;
- while(1){
- if(i==0 && j==dDimension){
- trace_printf("game over !\\n");
- break;
- }
- for(k=j;k<dDimension;k++){
- a[i]=k;
- dRet = Empress_Judge(i,a,dDimension);//判断i列之前部分是否冲突,0:不冲突; -1:冲突
- if(dRet == 0 && i<dDimension){
- break;
- }
- }
- //printf("k=%d\\n",k);
- if(dRet==0){
- dRet=-1;//重置状态
- if(i==dDimension-1){
- dCount++;
- empress_printf(dCount,a,dDimension);
- j=a[i]+1;
- //break;
- }else{
- j=0;
- i++;
- }
- continue;
- }
- if(k==dDimension && i>0){//倒退
- i--;
- j=a[i]+1;
- }
- }
- if(a != NULL)
- free(a);
- if(fp != NULL)
- fclose(fp);
- return dCount;
- }
- #endif
- //该片段来自于http://www.codesnippet.cn/detail/0501201511472.html
来源: http://www.codesnippet.cn/detail/0501201511472.html