精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>● Delphi>>Object Pascal语言>>八皇后非递规算法

主题:八皇后非递规算法
发信人: fishy(死鱼)
整理人: kingron(2001-03-05 16:15:26), 站内信件
作者:Fishy
下面是我的8皇后问题的非递归程序,希望可以带出一些讨论算法的人:)
在Borland Pascal 7.0下编译通过
ps:我很懒的,所以没写注释:p

{$A+,B-,D-,E-,F-,G+,I-,L-,N+,O-,P-,Q-,R-,S-,T-,V-,X-,Y-}
{$M 16384,0,655360}
const
  qn=8;
var
  step:integer;
  a:longint;
  i,q:array[1..qn]of integer;
  used1:array[1..qn]of boolean;
  used2:array[2..qn+qn]of boolean;
  used3:array[1-qn..qn-1]of boolean;

procedure out;
var
  i:integer;
begin
  inc (a);
  for i:=1 to qn do write(q[i]:3);
  writeln;
end;

begin
  fillchar (q,sizeof(q),0);
  fillchar (i,sizeof(i),0);
  fillchar (used1,sizeof(used1),false);
  fillchar (used2,sizeof(used2),false);
  fillchar (used3,sizeof(used3),false);
  step:=1;a:=0;

  repeat
    if step>qn then
     begin
       out;
       dec (step);                
       used1[q[step]]:=false;
       used2[q[step]+step]:=false;
       used3[q[step]-step]:=false;
       continue;
     end;
    inc (i[step]);
    if i[step]>qn then
     begin
       i[step]:=0;
       dec (step);
       used1[q[step]]:=false;
       used2[q[step]+step]:=false;
       used3[q[step]-step]:=false;
       continue;
     end;
    if used1[i[step]] or used2[i[step]+step] or used3[i[step]-step] then continue;
    q[step]:=i[step];
    used1[q[step]]:=true;
    used2[q[step]+step]:=true;
    used3[q[step]-step]:=true;
    inc (step);
  until step=0;

  writeln ('Total ',a,' answers.');
end.


----
Algorithm Data Struct Program
                       ------N. Wirth
酷码工作室

[关闭][返回]