掲示板システム
ホーム
アクセス解析
カテゴリ
ログアウト
ハノイの塔の解を教えてください (ID:23504)
名前
ホームページ(ブログ、Twitterなど)のURL (省略可)
本文
円盤 N枚の「ハノイの塔」対応版 30枚以上では画面から はみ出すかな。 64枚以上では計算不能(--;)… procedure TForm1.Button1Click(Sender: TObject); const SrcPole = 1; // 最初の柱番号 DstPole = 3; // 目的の柱番号 THICK = 14; // 円盤の厚さ DIFD = 15; // 円盤の径差 HPOS = 10; // 円盤の位置 var NumDisk: Integer; // 円盤の枚数 C: array of TColor; W: array of Integer; S: array of Integer; x: array of Integer; y: array of Integer; P: array[1..3]of Integer; H: array[1..3]of Integer; i: Integer; cnt, ans: Int64; ShowImage, HighSpeed: Boolean; procedure Carry(n, a, b: Integer); var t: Integer; begin Application.ProcessMessages; if Application.Terminated then exit; if n > 1 then Carry(n - 1, a, 6 - a - b); if ShowImage then begin if not CheckBox2.Checked then begin for t:=1 to 100 do begin Application.ProcessMessages; Sleep(10); if Application.Terminated then exit; end; end else begin Sleep(1); end; end else begin Sleep(0); end; inc(cnt); Memo1.Lines.Add(Format('%5d回目:円盤 %d を %d から %d に移す', [cnt, n, a, b])); TButton(Sender).Caption := Format('%d/%d',[cnt, ans]); if ShowImage then begin with Image1.Canvas do begin Pen.Color := clWhite; Brush.Color := clWhite; RectAngle(x[n]+S[n], y[n], x[n]+S[n]+W[n], y[n]+THICK); Pen.Color := clBlack; Brush.Color := C[n]; x[n] := P[b]; y[n] := H[b]; H[a] := H[a]+THICK; H[b] := H[b]-THICK; RectAngle(x[n]+S[n], y[n], x[n]+S[n]+W[n], y[n]+THICK); TextOut(x[n]+S[n]-2+ W[n] div 2, y[n]+1, IntToStr(n)); end; end; if n > 1 then Carry(n - 1, 6 - a - b, b); end; begin ShowImage := CheckBox1.Checked; HighSpeed := CheckBox2.Checked; with SpinEdit1 do begin MinValue := 1; MaxValue := 64; if Value < 1 then Value := 1; NumDisk := Value; end; Memo1.Clear; ans := Trunc(IntPower(2, NumDisk) - 1); cnt := 0; if ShowImage then begin Randomize; SetLength(C, NumDisk+1); for i:=1 to High(C) do C[i] := Random($28) shl 18 + Random($28) shl 10 + Random($28) shl 2 + $606060; SetLength(W, NumDisk+1); for i:=1 to High(W) do W[i] := i*DIFD + 20; SetLength(S, NumDisk+1); for i:=1 to High(S) do S[i] := (High(S)*DIFD - i*DIFD) div 2; P[1] := 10; P[2] := NumDisk*DIFD+25 + 10; P[3] := (NumDisk*DIFD+25)*2 + 10; H[SrcPole] := HPOS; H[SrcPole mod 3 + 1] := HPOS + THICK * NumDisk; H[(SrcPole+1) mod 3 + 1] := HPOS + THICK * NumDisk; SetLength(x, NumDisk+1); SetLength(y, NumDisk+1); with Image1.Canvas do begin Font.Size := 9; SetBkMode(Image1.Canvas.Handle, TRANSPARENT); Brush.Color := clWhite; RectAngle(0, 0, Width, Height); for i:=1 to NumDisk do begin x[i] := P[SrcPole]; y[i] := HPOS + THICK * i; Pen.Color := clBlack; Brush.Color := C[i]; RectAngle(x[i]+S[i], y[i], x[i]+S[i]+W[i], y[i]+THICK); TextOut(x[i]+S[i]-2+ W[i] div 2, y[i]+1, IntToStr(i)); end; end; end; TButton(Sender).Enabled := False; Carry(NumDisk, SrcPole, DstPole); TButton(Sender).Enabled := True; end;
←解決時は質問者本人がここをチェックしてください。
更新する
戻る
掲示板システム
Copyright 2021 Takeshi Okamoto All Rights Reserved.