the_king
مدیرکل انجمن
کد زیر مساله برج های هانوی را حل می کند :
کد:
program prg;
uses crt;
var
stn,stbeg,stfin,stadd:array[1..50] of integer;
n,top,beg,aux,fin,add,temp,i:integer;
procedure push(a,b,c,d:integer);
begin
top:=top+1;
stn[top]:=a;
stbeg[top]:=b;
stfin[top]:=c;
stadd[top]:=d;
end;
procedure pop(var n,beg,fin,add,top:integer);
begin
n:=stn[top];
beg:=stbeg[top];
fin:=stfin[top];
add:=stadd[top];
top:=top-1;
end;
procedure tower(n,beg,fin:integer);
label l1,l2,l3,l4,l5;
begin
top:=0;
l1: if n=1 then
begin
writeln (chr(beg+64),' -> ',chr(fin+64));
goto l5;
end;
l2: push(n,beg,fin,3);
n:=n-1;
case beg+fin of
1+2 : aux:=3;
1+3 : aux:=2;
2+3 : aux:=1;
end;
temp:=aux;
aux:=fin;
fin:=temp;
goto l1;
l3: writeln (chr(beg+64),' -> ',chr(fin+64));
l4: push(n,beg,fin,5);
n:=n-1;
temp:=beg;
beg:=aux;
aux:=temp;
goto l1;
l5: if top=0 then exit;
pop(n,beg,fin,add,top);
case beg+fin of
1+2 : aux:=3;
1+3 : aux:=2;
2+3 : aux:=1;
end;
if add=3 then goto l3;
if add=5 then goto l5;
end;
begin
clrscr;
tower(3,1,3);
end.