#include <bits/stdc++.h>

typedef long long LL;

const int N = 1e3 + 7;
const int MOD = 998244353;

const int X[] = {1, -1, 0, 0};
const int Y[] = {0, 0, 1, -1};

int n, m, ans;
int a[N][N], c[N][N];

template<typename T> void solve(T &q, int co) {
  auto [v, x, y] = q.top();
  q.pop();
  if(c[x][y] == co) {
    solve(q, co);
    return ;
  }
  c[x][y] = co;
  for(int i = 0; i < 4; ++i) {
    int u = x + X[i], v = y + Y[i];
    if(u >= 1 && u <= n && v >= 1 && v <= m) {
      if(!c[u][v])
	q.push({a[u][v], u, v});
      else if(c[u][v] != co) {
	printf("%d\n", ans);
	exit(0);
      }
    }
  }
}

int main() {

  scanf("%d%d", &n, &m);
  for(int i = 1; i <= n; ++i)
    for(int j = 1; j <= m; ++j)
      scanf("%d", &a[i][j]);

  c[1][1] = 1, c[n][m] = 2;
  std::priority_queue<std::tuple<int, int, int>,
		      std::vector<std::tuple<int, int, int>>,
		      std::greater<std::tuple<int, int, int>>> p, q;
  p.push({a[1][2], 1, 2});
  p.push({a[2][1], 2, 1});
  q.push({a[n - 1][m], n - 1, m});
  q.push({a[n][m - 1], n, m - 1});

  while(true) {
    ++ans;
    solve(p, 1);
    ++ans;
    solve(q, 2);
  }
  
  return 0;

}