首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > N皇后问题
【标  题】:N皇后问题
【关键字】:
【来  源】:网络

N皇后问题

一【题目】N皇后问题(含八皇后问题的扩展,规则同八皇后):在N*N的棋盘上,放置N个皇
后,要求每一横行每一列,每一对角线上均只能放置一个皇后,求解可能的方案及方案数。
下面是算法的实现源码,请大家讨论。
      const max=8;
      var i,j:integer;
      a:array[1..max] of 0..max; {放皇后数组}
      b:array[2..2*max] of boolean; {/对角线标志数组}
      c:array[-(max-1)..max-1] of boolean; {\对角线标志数组}
      col:array[1..max] of boolean; {列标志数组}
      total:integer; {统计总数}
      procedure output; {输出}
      var i:integer;
    begin
      write('No.':4,'[',total+1:2,']');
      for i:=1 to max do
             write(a[i]:3);write(' ');
      if (total+1) mod 2 =0
            then writeln; inc(total);
    end;
     function ok(i,dep:integer):boolean; {判断第dep行第i列可放否}
        begin
           ok:=false;
             if ( b[i+dep]=true) and ( c[dep-i]=true) {and (a[dep]=0)} and
                         (col[i]=true)  
             then ok:=true
          end;
      procedure try(dep:integer);
          var i,j:integer;
         begin
            for i:=1 to max do {每一行均有max种放法}
                if ok(i,dep) then
                 begin
                 a[dep]:=i;
                   b[i+dep]:=false; {/对角线已放标志}
                   c[dep-i]:=false; {\对角线已放标志}
                 col[i]:=false; {列已放标志}
            if dep=max then output
                 else try(dep+1); {递归下一层}
              a[dep]:=0; {取走皇后,回溯}
              b[i+dep]:=true; {恢复标志数组}
              c[dep-i]:=true;
              col[i]:=true;
       end;
      end;
    begin
        for i:=1 to max do
              begin
               a[i]:=0;col[i]:=true;
              end;
              for i:=2 to 2*max do
                 b[i]:=true;
              for i:=-(max-1) to max-1 do
                  c[i]:=true;
             total:=0;
            try(1);
           writeln('total:',total);
end.
链表的运算(01):【上一篇】
数据结构题集--数组(二维数组-1):【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • JDBC数据库编程高级问题
  • 你是否为了你的站点文章过多而反复做链接上一页
  • nc.exe高级技巧应用汇总
  • 感觉自己越来越容易被感动了!
  • Oracle初学者笔记(二)
  • [Python for Series 60 的开发指南] 介绍
  • 3d圆环旋转
  • 《.NET Compact Framework 移动开发指南》,即将与大家见面
  • 利用Javascript脚本捕获键盘事件
  • 2006 年 XML 大事记
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 软讯网络 All Rigths Reserved.