#include<bits/stdc++.h>
using namespace std;
const int maxsize=110;
struct eage{
int x,h;
}p[maxsize*maxsize];
int d[3][3];
int n,m,ans;
int f[maxsize*maxsize];
bool cmp(eage x,eage y){
return x.h>y.h;
}
bool check(int i,int j){
for(int k=1;k<=2;k++)
if((p[i].x+d[k][1]==p[j].x||p[i].x+d[k][2]==p[j].x)&&p[i].h<p[j].h)return 1;
return 0;
}
int dp(){
int ans=0;
for(int i=1;i<=n*m;i++){
f[i]=1;
for(int j=i-1;j;j--)
if(check(i,j)){
f[i]=max(f[i],f[j]+1);
}
ans=max(ans,f[i]);
}
return ans;
}
int main(){
cin>>n>>m;
d[1][1]=m;
d[1][2]=-m;
d[2][1]=1;
d[2][2]=-1;
int mn=m*n;
for(int i=1;i<=mn;i++){
cin>>p[i].h;
p[i].x=i;
}
sort(p+1,p+1+mn,cmp);
int ans=dp();
cout<<ans;
return 0;
}