八皇后的简单解法

#include <iostream.h>
#include<io.h>
const int QUENS = 7;
int getcol(int q[],int n,const int firstCol)
{//q表示每个皇后的列位置,firstCol是搜索列位置时的起始位置
//n表示正在搜索第n个皇后的列位置,皇后的名称从0--n编号,也是皇后的行号
 bool b = true;
 int i = firstCol;
 for (i = firstCol; i<=QUENS ; i++) {
  for (int j=0; j<n; j++) {
   if(q[j] == i || (n+q[j]==i+j)||(n+i == j+q[j])){
    b = false;
    break;
   }
  }
  if(j == n)
    return i;
  else if(firstCol > QUENS) return firstCol;
 }
 if(!b) return QUENS+1;
}
void EQ(int q[],int n){
 void disp(int[]);
 int col = QUENS+1;
 bool b = true;
 int firstCol = 0;
 while (QUENS >= (col=getcol(q,n,firstCol))){
  if(QUENS == n){
   q[n] = col;
   disp(q);
   return ;
  }
  else{
   q[n] = col;
   firstCol = col +1;
   EQ(q,n+1);
  }
 }
 
}
void disp(int q[])
{//显示一种排列
 static count = 0;
 count++;
 cout<<"number "<<count<<" : ";
 for (int i=0; i<=QUENS; i++)
  cout<<q[i]+1<<" ";
 cout<<endl;
}
void outTofile()
{//由于结果比较多,所以把结果重定向输出到文件里头了,文件名是EightQuen.txt
 int old = _dup(1);
 FILE* pf;
 pf = fopen("EightQuen.txt","w");
 if(!pf)  throw 0;
 _dup2((fileno(pf)),_fileno(stdout));
 int q[8];
 EQ(q,0);
fclose(pf);
 _dup2(old,_fileno(stdout));

}
void main()
{
outTofile();
}

posted on 2007-09-14 14:41 zlf 阅读(574) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2007年9月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

统计

常用链接

留言簿(1)

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜