#include<bits/stdc++.h>
using namespace std;
int n,m,a[1005][1005],p;
bool v[1005][1005];
int l=0,r=1000,ans=0;
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
struct node{
int x,y;
};
bool bfs(int mid){
memset(v,0,sizeof(v));
queue<node> q;
node start;
start.x=1,start.y=1;
q.push(start);
v[1][1]=1;
while(!q.empty()){
node head=q.front();
for(int i=0;i<=3;i++){
int xx=head.x+dx[i];
int yy=head.y+dy[i];
if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&!v[xx][yy]&&mid>=a[xx][yy]){
if(xx==n)return 1;
v[xx][yy]=1;
node next;
next.x=xx,next.y=yy;
q.push(next);
}
}
q.pop();
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
while(l<=r){
p=(l+r)>>1;
if(bfs(p)) r=p-1,ans=p;
else l=p+1;
}
cout<<ans;
return 0;
}