Код
program recursion;
const maxn=10;
var a,b:array[1..maxn,1..maxn]of integer;
i1,j1:integer;
i,j,n:integer;
cou:integer;
procedure init;
begin
readln(n);
for i:=1 to n do
for j:=1 to n do
read(a[i,j]);
end;
procedure solve(i,j:integer);
begin
if (i<1) or (i>n) or (j<1) or (j>n) or (a[i,j]=1) then exit;
if b[i,j]>cou then b[i,j]:=cou;
a[i,j]:=1;
inc(cou);
solve(i+1,j);
solve(i-1,j);
solve(i,j+1);
solve(i,j-1);
dec(cou);
end;
procedure out;
begin
writeln(b[i1,j1]);
end;
begin
init;
cou:=0;
for i:=1 to n do
for j:=1 to n do
b[i,j]:=maxint;
for i:=1 to n do
for j:=1 to n do
if a[i,j]=2 then
begin
i1:=i;
j1:=j;
end;
solve(1,1);
out;
end.