#define ll long long
#pragma warning(disable : 4996)
#include <iostream>
#include<string>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <cmath>
#include<cstdio>
using namespace std;
struct zuobiao
{
int x;
int y;
}z[1000001];
int p[1005][1005],n,m,ans;
int xj[] = { 0,0,1,-1 };
int yj[] = { 1,-1,0,0 };
bool v[1005][1005];
bool bfs(int s)
{
int l = 0, r = 1;
z[1].x = 1; z[1].y = 1;
memset(v, 0, sizeof(v));
while(l<r)
{
++l;
v[z[l].x][z[l].y] = 1;
for (int i = 0; i <= 3; ++i)
{
int xx = z[l].x + xj[i];
int yy = z[l].y + yj[i];
if (xx<1 || yy<1 || xx>n || yy>m)
continue;
if (p[xx][yy] <= s && v[xx][yy] != 1)
{
z[++r].x = xx; z[r].y = yy;
v[xx][yy] = 1;
}
if (xx == n)return 1;
}
}
return 0;
}
int main()
{
cin >> n >> m;
int max = 0;
for(int i=1;i<=n;++i)
for (int j = 1; j <= m; ++j)
{
cin >> p[i][j];
if (p[i][j] > max)
max = p[i][j];
}
int zb=0, yb=max;
while (zb <= yb)
{
int mid = (zb + yb) / 2;
if (bfs(mid))
{
yb=mid-1;
ans = mid;
}
else zb=mid+1;
}
cout << ans;
return 0;
}