哎,这题还真不需要牛人来解决,死套公式实现了一下,貌似能出结果.
想优化这种算法得在逻辑表达式化简上下工夫,那才是牛人干的呢.
program Project2;
{$APPTYPE CONSOLE}
type
TSet = set of Byte;
TResult = array of TSet;
var
M, N: Integer;
NodeNum: Integer;
NewSet: TSet;
i, j, k: Integer;
d, Index: Integer;
r, tr: TResult;
Add: Boolean;
Best, BestPos: Integer;
function Delta(const Index, d: Integer): Integer;
begin
case d of
1: Result:=Index;
2: if Index<M then
Result:=-1
else
Result:=Index-M;
3: if (Index mod M)>=(M-1) then
Result:=-1
else
Result:=Index+1;
4: if (Index div M)>=(N-1) then
Result:=-1
else
Result:=Index+M;
5: if (Index mod M)=0 then
Result:=-1
else
Result:=Index-1
else
Result:=-1
end
end;
function TrueLength(const ASet: TSet): Integer;
var
i: Integer;
begin
Result:=0;
for i:=0 to NodeNum-1do
if (i in ASet) then
Inc(Result)
end;
procedure Print(const ASet: TSet);
var
x, y, Index: Integer;
begin
for x:=0 to N-1do
begin
for y:=0 to M-1do
begin
Index:=x*M+y;
if (Index in ASet) then
Write('0': 2)
else
Write('*': 2)
end;
WriteLn
end
end;
begin
Write('M=');
ReadLn(M);
Write('N=');
ReadLn(N);
NodeNum:=M*N;
if (NodeNum>0) and (NodeNum<256) then
begin
for d:=1 to 5do
begin
Index:=Delta(0, d);
if Index>=0 then
begin
SetLength(r, Length(r)+1);
r[Length(r)-1]:=[Index]
end
end;
for i:=1 to NodeNum-1do
begin
SetLength(tr, Length(r));
for j:=0 to Length(r)-1do
tr[j]:=r[j];
SetLength(r, 0);
for d:=1 to 5do
begin
Index:=Delta(i, d);
if Index>=0 then
for j:=0 to Length(tr)-1do
begin
NewSet:=tr[j]+[Index];
Add:=True;
k:=0;
while Add and (k<Length(r))do
if NewSet*r[k]=r[k] then
Add:=False
else
if NewSet*r[k]=NewSet then
begin
r[k]:=r[Length(r)-1];
SetLength(r, Length(r)-1)
end
else
Inc(k);
if Add then
begin
SetLength(r, Length(r)+1);
r[Length(r)-1]:=NewSet
end
end
end
end;
Best:=MaxInt;
BestPos:=-1;
for i:=0 to Length(r)-1do
begin
j:=TrueLength(r);
if j<Best then
begin
Best:=j;
BestPos:=i
end
end;
if BestPos>=0 then
Print(r[BestPos])
end
else
WriteLn('Error');
ReadLn
end.