#include using namespace std; const int INF = 1<<30; const int MOD = 998244353; //const long long INF = 1LL<<60; using graph = vector>; using ll = long long; int dx[] = {1, 0, -1, 0}; int dy[] = {0, -1, 0, 1}; void print(vector> & vec, int h, int w){ for (int i=0; i < h; i++){ for (int j=0; j < w; j++){ cout << vec[i][j]; } cout << endl; } } int main(){ int h, w; cin >> h >> w; vector> a(h, vector(w)); for (int i=0; i < h; i++) for (int j=0; j < w; j++) cin >> a[i][j]; vector> region1(h, vector(w)), region0(h, vector(w)); priority_queue> pq1, pq0; pq1.push(make_tuple(-a[0][0], 0, 0)); pq0.push(make_tuple(-a[h-1][w-1], h-1, w-1)); for (int i=1; i <= h*w; i++){ if (i % 2 == 1){ int v, x, y; tie(v, x, y) = pq1.top(); pq1.pop(); if (region0[x][y] != 0){ cout << i-2 << endl; return 0; } region1[x][y] = 2; for (int j=0; j < 4; j++){ int nx = x + dx[j]; int ny = y + dy[j]; if (nx < 0 || h <= nx || ny < 0 || w <= ny) continue; if (region1[nx][ny] == 0){ region1[nx][ny] = 1; pq1.push(make_tuple(-a[nx][ny], nx, ny)); } continue; } } if (i % 2 == 0){ int v, x, y; tie(v, x, y) = pq0.top(); pq0.pop(); region0[x][y] = 2; //cout << i << x << y << v << endl; if (region1[x][y] != 0){ cout << i-2 << endl; return 0; } for (int j=0; j < 4; j++){ int nx = x + dx[j]; int ny = y + dy[j]; if (nx < 0 || h <= nx || ny < 0 || w <= ny) continue; if (region0[nx][ny] == 0){ region0[nx][ny] = 1; pq0.push(make_tuple(-a[nx][ny], nx, ny)); } } } } }