请用1-16中的数字填满空格,使四个角,横向,竖向,对角线上的数字相加的和都等于34
代码:
procedure tform1.compuer(ifirst: byte);
var
i,j,count:integer;
str,strtemp:string;
a:array[1..16] of integer;
r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16:integer;
strlist:tstringlist;
function compabefore(i:integer): boolean;
var
j:integer;
begin
result:=false;
for j:=1 to i-1 do
begin
if a[j]=a then
begin
result:=true;
break;
end;
end;
end;
begin
count:=0;
a[1]:=ifirst;
for r2:=1 to 16 do
begin
a[2]:=r2;
if compabefore(2) then continue;
for r3:=1 to 16 do
begin
a[3]:=r3;
if compabefore(3) then continue;
a[4]:=34-(a[1]+a[2]+a[3]);
if compabefore(4) then continue;
if a[4]>16 then continue;
for r5:=1 to 16 do
begin
a[5]:=r5;
if compabefore(5) then continue;
for r6:=1 to 16 do
begin
a[6]:=r6;
if compabefore(6) then continue;
for r7:=1 to 16 do
begin
a[7]:=r7;
if compabefore(7) then continue;
a[8]:=34- (a[5]+a[6]+a[7]);
if compabefore(8) then continue;
if a[8]>16 then continue;
for r9:=1 to 16 do
begin
a[9]:=r9;
if compabefore(9) then continue;
for r10:=1 to 16 do
begin
a[10]:=r10;
if compabefore(10) then continue;
for r11:=1 to 16 do
begin
a[11]:=r11;
if compabefore(11) then continue;
a[12]:=34- (a[9]+a[10]+a[11]);
if compabefore(12) then continue;
if a[12]>16 then continue;
if a[1]+a[5]+a[9]<>a[4]+a[7]+a[10] then continue;
a[13]:=34- (a[1]+a[5]+a[9]);
if a[13]>16 then continue;
if compabefore(13) then continue;
a[14]:=34-(a[2]+a[6]+a[10]);
if a[14]>16 then continue;
if compabefore(14) then continue;
a[15]:=34-(a[3]+a[7]+a[11]);
if a[15]>16 then continue;
if compabefore(15) then continue;
if (a[1]+a[6]+a[11]<>a[4]+a[8]+a[12]) or (a[1]+a[6]+a[11]<>a[13]+a[14]+a[15])then continue;
a[16]:=34-(a[1]+a[6]+a[11]);
if a[16]>16 then continue;
if compabefore(16) then continue;
inc(count);
application.processmessages;
if count>1000 then exit;
memo1.lines.add(\';=======第\';+inttostr(count)+\';个解========\';);
for i:=1 to 4 do
begin
str:=\';\';;
for j:=1 to 4 do
begin
strtemp:=inttostr(a[(i-1)*4+j]);
if length(strtemp)=1 then
str:=str+strtemp+\'; \';
else
str:=str+strtemp+\'; \';;
end;
memo1.lines.add(trim(str));
end;
end;
end;
end;
end;
end;
end;
end;
end;
end; |