8皇后问题的非递归程序

     阅读 518 次    更新时间:2014/4/18    
下面是我的8皇后问题的非递归程序,希望可以带出一些讨论算法的人:) 

下面是我的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.

 
 

Copyright 2003-2008 All Rights Reserved 自由风工作室 版权没有 [湘ICP备06002185号]
.