#include<bits/stdc++.h>
using namespace std;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int n,m;
int a[1005][1005];
int book[1005][1005];
int f[1005][1005];
int maxx=0;
int dfs(int x,int y){
if(f[x][y]!=0) return f[x][y];
f[x][y]=1;
for(int i=0;i<4;i++){
int p=x+dx[i];
int q=y+dy[i];
if(!book[p][q] && a[x][y]%a[p][q]==0 && a[x][y]!=a[p][q] && p>=1 && p<=n && q>=1 &&q<=m){
book[p][q]=true;
f[x][y]=max(f[x][y],1+dfs(p,q));
book[p][q]=false;
}
}
return f[x][y];
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
book[i][j]=true;
int cnt=dfs(i,j);
maxx=max(maxx,cnt);
book[i][j]=false;
}
}
cout<<maxx;
return 0;
}