// Arup Guha
// 4/11/2023
// Solution to 2017 MAPS Problem F: Muddy Hike

import java.util.*;
import java.io.*;

public class muddyhike {

	public static int r;
	public static int c;
	public static int[][] g;
	
	public static void main(String[] args) throws Exception {
	
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer tok = new StringTokenizer(stdin.readLine());
		
		// Read grid.
		r = Integer.parseInt(tok.nextToken());
		c = Integer.parseInt(tok.nextToken());
		g = new int[r][c];
		for (int i=0; i<r; i++) {
			tok = new StringTokenizer(stdin.readLine());
			for (int j=0; j<c; j++)
				g[i][j] = Integer.parseInt(tok.nextToken());
		}
		
		// Create edges and then sort - weights are max vertex weight.
		ArrayList<edge> eList = new ArrayList<edge>();
		for (int i=0; i<r; i++) {
			for (int j=0; j<c; j++) {
				if (i+1 < r) eList.add(new edge(c*i+j, c*(i+1)+j, Math.max(g[i][j], g[i+1][j])));
				if (j+1 < c) eList.add(new edge(c*i+j, c*i+j+1, Math.max(g[i][j], g[i][j+1])));
			}
		}
		Collections.sort(eList);
		
		// First column is in one group, so is last, merge them...
		djset dj = new djset(r*c);
		for (int i=0; i<r-1; i++) {
			dj.union(c*i, c*(i+1));
			dj.union(c*i+c-1, c*(i+1)+c-1);
		}
		
		// Go through the edges in sorted order and union those vertices.
		int idx;
		for (idx=0; idx<eList.size(); idx++) {
			dj.union(eList.get(idx).u, eList.get(idx).v);
			if (dj.find(0) == dj.find(r*c-1)) break;
		}
		
		// This is our answer.
		System.out.println(eList.get(idx).w);
	}
}

class edge implements Comparable<edge> {

	public int u;
	public int v;
	public int w;
	
	public edge(int a, int b, int c) {
		u = a;
		v = b;
		w = c;
	}
	
	public int compareTo(edge other) {
		if (w != other.w) return w - other.w;
		if (u != other.u) return u - other.u;
		return v - other.v;
	}
}

class djset {
	
	public int[] par;
	
	public djset(int n) {
		par = new int[n];
		for (int i=0; i<n; i++)
			par[i] = i;
	}
	
	public int find(int u) {
		if (par[u] == u) return u;
		return par[u] = find(par[u]);
	}
	
	public boolean union(int u, int v) {
		u = find(u);
		v = find(v);
		if (u == v) return false;
		par[v] = u;
		return true;
	}
}