delphi实现汉诺塔

//汉诺塔游戏,就是依次把最大的盘子移动出来,n-1,n-1-1,一直到可以n=1.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    edt1: TEdit;
    mmo1: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure MoveHanoiTower(n:Integer;x,y,z:char);
    procedure btn1Click(Sender: TObject);
    procedure moveonedisk(a,b:char);
  private
    { Private declarations }
    totaltxt:string;
    str:string;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  mmo1.Text := '';
  totaltxt := '';
end;

procedure TForm1.moveonedisk(a,b:char);
begin
  str := 'Move from ' + a + ' to ' + b +#13#10;
  totaltxt := totaltxt + str;
end;

procedure TForm1.MoveHanoiTower(n: Integer; x, y, z: char);
begin
  if n = 1 then
    moveonedisk(x,z)
  else
  begin
    MoveHanoiTower(n-1,x,z,y);
    moveonedisk(x,z);
    MoveHanoiTower(n-1,y,x,z);
  end;
end;

procedure TForm1.btn1Click(Sender: TObject);
var N:Integer;
  x,y,z:Char;
begin
  mmo1.Clear;
  totaltxt := '';
  n:= StrToInt(Trim(edt1.Text));
  x := 'x';
  y := 'y';
  z := 'z';
  if n = 1 then
    moveonedisk(x,z)
  else
    MoveHanoiTower(n,x,y,z);
  mmo1.Text := totaltxt;
end;

end.
 

你可能感兴趣的:(递归,汉诺塔)