Google Treasure Hunt 2008 走格式题解

ahjoe 2008-12-24 05:43:54
题目: 34x68的格子,从左上角到右下角,有多少种走法。规则:只能向右或向下行走。
解题方法: 从一个格子到右下角的走法数量,等于它右边格子与下边格子的走法数量之和,从最下边的格子或最右边的格子到右下角只有一种走法。
结果: 0294692427022540894366527900
计算用时: 瞬间
注: 用String做大数计算。


unit GoogleHunt2u;

interface

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

type
TForm1 = class(TForm)
SpinEdit1: TSpinEdit;
Label1: TLabel;
Label2: TLabel;
SpinEdit2: TSpinEdit;
Button1: TButton;
Edit1: TEdit;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

var
VArr: array [0..100, 0..100] of string;

function BigIntAdd(V1, V2: string): string;
var
i: integer;
max1, max2: integer;
max: integer;
v: integer;
begin
if V1[1] = '0' then
max1 := Length(V1) - 1
else
max1 := Length(V1);
if V2[1] = '0' then
max2 := Length(V2) - 1
else
max2 := Length(V2);
if max1 > max2 then
max := max1 + 1
else
max := max2 + 1;

while Length(V1) < max do
begin
V1 := '0' + V1;
end;
while Length(V2) < max do
begin
V2 := '0' + V2;
end;

SetLength(Result, max);
v := 0;
for i := max downto 1 do
begin
v := Byte(V1[i]) + Byte(V2[i])-Byte('0')*2 + v;
Result[i] := Char((v mod 10) + Byte('0'));
v := v div 10;
end;
end;

function CountRoute(W, H: integer): string;
begin
if (W = 1) or (H = 1) then
Result := '1'
else
begin
if VArr[W-1][H] = '' then
begin
VArr[W-1][H] := CountRoute(W-1, H);
VArr[H][W-1] := VArr[W-1][H];
end;
if VArr[W][H-1] = '' then
begin
VArr[W][H-1] := CountRoute(W, H-1);
VArr[H-1][W] := VArr[W][H-1];
end;
Result := BigIntAdd(VArr[W-1][H], VArr[W][H-1]);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
W, H: integer;
begin
W := SpinEdit1.Value;
H := SpinEdit2.Value;
Edit1.Text := CountRoute(W, H);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
FillChar(VArr, sizeof(VArr), 0);
end;

end.

...全文
68 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rcaicc 2008-12-24
  • 打赏
  • 举报
回复
棒~~
收藏了.
这种问题给我直接就是递归.估计34*68能算死
ahjoe 2008-12-24
  • 打赏
  • 举报
回复
标题打错了,版主帮我。"走格子题解"
ahjoe 2008-12-24
  • 打赏
  • 举报
回复
小技巧: 用一个2维数组保存特定宽高格子的走法数量,避免重复计算。

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧