如何用递归法和迭代法求解汉诺塔问题?(100分)

  • 主题发起人 主题发起人 7030
  • 开始时间 开始时间
7

7030

Unregistered / Unconfirmed
GUEST, unregistred user!
最好能附上思路
 
都这么经典的东西了
if (disc>0) {
move(disc-1, a,c,b)
writeln("move disc from a to b");
move(disc-1, b,c,a);
}
 
很多关于算法的书上都有例子,这是最经典的题目
 
>>

program fanta;

uses crt,graph;

const
graphpath='./';
bc=1;co=15;pc=4;

var
i:byte;
n:byte;
gm1,gm2:integer;
k,g:integer;
r:array [1..3] of byte;
nr:array [1..3,1..30] of byte;

procedure stop;
begin
closegraph;
halt;
end;

procedure hua(z,d,s:byte);
begin
bar(107+(z-1)*213-d*k,479-s*g+1,107+(z-1)*213+d*k,479-(s-1)*g);
end;

procedure ot(f,t:byte);
begin
setfillstyle(0,1);
hua(f,nr[f,r[f]],r[f]);
line(107+(f-1)*213,479-r[f]*g+1,107+(f-1)*213,479-(r[f]-1)*g);
r[f]:=r[f]-1;
setfillstyle(1,pc);
r[t]:=r[t]+1;nr[t,r[t]]:=nr[f,r[f]+1];
hua(t,nr[t,r[t]],r[t]);
gotoxy (1,1);
if (ord(ReadKey)=27) then stop;
end;

procedure yi(f,t,s:byte);
begin
if s=1 then
ot(f,t)
else
begin
yi(f,6-f-t,s-1);
ot(f,t);
yi(6-f-t,t,s-1);
end;
end;

begin
repeat
write('n(2<=n<=30)=');
readln(n);
until (n>=2) and (n<=30);
gm1:=vga;gm2:=vgahi;initgraph(gm1,gm2,graphpath);
r[2]:=0;r[3]:=0;r[1]:=n;
k:=620 div 6 div n;g:=459 div n;
setbkcolor(bc);setcolor(co);setfillstyle(1,pc);
for i:=0 to 2 do line(107+i*213,0,107+i*213,479);
for i:=1 to n do
begin
nr[1,i]:=n+1-i;
hua(1,i,n+1-i);
end;
if (ord(Readkey)=27) then stop;
yi(1,3,n);
stop;
end.
 
多人接受答案了。
 

Similar threads

S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
900
SUNSTONE的Delphi笔记
S
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
后退
顶部