var
i,j,k,n,m,p,q:longint;
b,t:array[-10..1000,-10..1000] of longint;
a,x,y:array[-10..100000] of longint;
procedure kuaipai(m,n:longint);
var
i,j,k,q:longint;
begin
i:=m;
j:=n;
k:=a[(n+m) div 2];
repeat
begin
while a[i]<k do inc(i);
while a[j]>k do dec(j);
if i<=j then
begin
q:=a[i];a[i]:=a[j];a[j]:=q;
q:=x[i];x[i]:=x[j];x[j]:=q;
q:=y[i];y[i]:=y[j];y[j]:=q;
inc(i);
dec(j);
end;
end;
until i>j;
if j>m then kuaipai(m,j);
if i<n then kuaipai(i,n);
end;
begin
readln(n,m);
k:=0;
for i:=1 to n do
for j:=1 to m do
begin
inc(k);
read(a[k]);
b[i,j]:=a[k];
x[k]:=i;
y[k]:=j;
end;
kuaipai(1,n*m);
for i:=0 to n+1 do
for j:=0 to m+1 do
t[i,j]:=0;
for i:=1 to m*n do
begin
p:=x[i];
q:=y[i];
k:=1;
if (k<t[p+1,q]+1) and (a[i]>b[p+1,q]) then k:=t[p+1,q]+1;
if (k<t[p-1,q]+1) and (a[i]>b[p-1,q]) then k:=t[p-1,q]+1;
if (k<t[p,q+1]+1) and (a[i]>b[p,q+1]) then k:=t[p,q+1]+1;
if (k<t[p,q-1]+1) and (a[i]>b[p,q-1]) then k:=t[p,q-1]+1;
t[p,q]:=k;
end;
k:=1;
for i:=1 to n do
for j:=1 to m do
if k<t[i,j] then k:=t[i,j];
writeln(k);
end.