#include<bits/stdc++.h>
using namespace std;
int n,m,a[1005][1005],ans,vis[1005][1005];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
typedef pair<int,int> Pair;
bool ok(int x,int y){
if(x<1||x>n)return false;
if(y<1||y>m)return false;
if(vis[x][y])return false;
return true;
}
bool bfs(int cur){
queue<Pair> q;
memset(vis,0,sizeof(vis));
q.push(make_pair(1,1));
vis[1][1]=1;
while(!q.empty()){
Pair t=q.front();
q.pop();
vis[t.first][t.second]=1;
for(int i=0;i<4;i++){
int X=t.first+dx[i];
int Y=t.second+dy[i];
if(ok(X,Y)){
if(a[X][Y]>cur)continue;
else if(X==n){
return 1;
}
else {
q.push(make_pair(X,Y));
}
}
}
}
return 0;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
int l=0,r=1005;
while(l<=r){
int mid=(l+r)>>1;
if(bfs(mid)){
r=mid-1;
ans=mid;
}
else {
l=mid+1;
}
}
cout<<ans;
return 0;
}