关于九皇后算法

#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("\n");
}
/*考虑下一个皇后*/
if(pos[i]<=N&&j<N)
{
   j=j+1;
}
else {/*返回考虑上一个皇后。*/
   pos[j] = 0;
   j = j- 1;
}
  }
    return 0;
}

 

posted on 2016-03-22 22:18  丰泽园的天空  阅读(950)  评论(0编辑  收藏  举报

导航