一个程序:用递归算法(回溯法)做八皇后问题?
收起
知与谁同
2018-07-21 11:43:29
1571
0
1
条回答
写回答
取消
提交回答
-
这个应该不错
var a:array[0..11] of integer;
n,k,t:integer;
procedure p(k:integer);
var i,j:integer;
g:boolean;
begin
if k>n then begin
for i:=1 to n-1 do
write(a[i],' ');
writeln(a[n]);
t:=t+1;
end
else begin
for i:=1 to n do begin
g:=true;
for j:=1 to k-1 do
if (i=a[j]) or (abs(i-a[j])=abs(k-j)) then g:=false;
if g then
begin
a[k]:=i;
p(k+1);
end;
end;
end;
end;
begin
readln(n);
t:=0;
k:=1;
p(k);
if t=0 then writeln('no solute!');
if t>0 then writeln(t);
end.
2019-07-17 22:55:30