import java.util.Scanner;
public class Main{
static int n;
static int m;
static int flag;
static int mid;
static int N = 1010;
static int a[][] = new int[N][N];
static int vis[][] = new int[N][N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
int res = 0;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
a[i][j] = sc.nextInt();
res = Math.max(res,a[i][j]);
}
}
int l = 0,r = res - 1;
while(l + 1 != r){
mid = l + r >>1;
flag = 0;
dfs(1,1,mid);
if(flag == 1){
r = mid;
}
else l = mid;
}
System.out.println(r);
}
public static void dfs(int x,int y,int mid){
if(x == n){
flag = 1;
}
int d[][] = new int[][]{{0,-1},{-1,0},{0,1},{1,0}};
for(int i = 0;i < 4;i++){
int xx = x + d[i][0];
int yy = y + d[i][1];
if(xx >= 1 && yy >= 1 && xx <= n && yy <= m){
if(vis[xx][yy] == 0 && a[xx][yy] <= mid){
vis[xx][yy] = 1;
dfs(xx,yy,mid);
vis[xx][yy] = 0;
if(flag == 1) break;
}
}
}
}
}