Код
program my;
uses crt; const num=10;
type my1=array[1..num,1..num] of char;
type my2=array[1..num,1..num] of char;
var
m,n,i,j,ci,cj:byte;
k:string;
min,el:integer;
opn:longint;
a:my1;
b:my2;
F,F1:text;
function odnor:byte;
begin
for i:=1 to n do
begin
for j:=1 to m do
begin
if b[i,j] = b[1,1] then
inc(el);
end;
end;
if el=n*m then odnor:=1 else odnor:=0;
end;
{////////////////////////////////////////////////////////////////////////////}
procedure selector(ci,cj:byte);
begin
case b[ci,cj] of
'1': begin b[ci,cj]:='3'; exit; end;
'2': begin b[ci,cj]:='1'; exit; end;
'3': begin b[ci,cj]:='2'; exit; end;
end;
end;
{////////////////////////////////////////////////////////////////////////////}
procedure changecolor(i,j:byte);
begin
selector(i,j);
if (i > 1) then
selector(i-1,j);
if (j < m) then
selector(i,j+1);
if (i < n) then
selector(i+1,j);
if (j > 1) then
selector(i,j-1);
end;
{////////////////////////////////////////////////////////////////////////////}
procedure forw(i,j:byte);
begin
inc(opn);
if odnor = 0 then
begin
changecolor(i,j);
if (i > 1) then
forw(i-1,j);
if (j < m) then
forw(i,j+1);
if (i < n) then
forw(i+1,j);
if (j > 1) then
forw(i,j-1);
end
else
min:=opn;
end;
{////////////////////////////////////////////////////////////////////////////}
{//////////////////////////// Reading from input file ///////////////////////}
begin clrscr;
assign(F,'input.txt');
reset(F);
read(F,n);
readln(F,m);
for i:=1 to n do
begin
readln(F,k);
for j:=1 to m do
begin
a[i,j]:=k[j];
b[i,j]:=k[j];
write(a[i,j]);
end; writeln;
end;
close(F);
{////////////////////////////////////////////////////////////////////////////}
writeln;
writeln;
for i:=1 to n do
begin
for j:=1 to m do
begin
opn:=0;
forw(i,j);
end; writeln;
end;
for i:=1 to n do
begin
for j:=1 to m do
begin
write(b[i,j]);
end; writeln;
end;
writeln;
writeln(min);
readkey;
end.