#include using namespace std; using ll = long long; using ull = unsigned long long; using Matrix = vector>; const int inf = 1000000000; const ll INF = 1000000000000000000; const ll mod = 998244353; const ull mod_hash = (1UL << 61) - 1; const vector dx = {0, 1, 0, -1, 1, 1, -1, -1}; const vector dy = {1, 0, -1, 0, 1, -1, 1, -1}; int main(){ int H,W;cin>>H>>W; vector> G(H,vector(W)); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) cin>>G[i][j]; set seen; set> zero, one; one.insert({G[0][1], 1}); one.insert({G[1][0], W}); zero.insert({G[H-1][W-2], (H-1)*W + W - 2}); zero.insert({G[H-2][W-1], (H-2)*W + W - 1}); seen.insert(0); seen.insert((H - 1) * W + W - 1); int turn = 1; int ans = 0; while(true){ pair ne; if(turn&1){ ne = *one.begin(); one.erase(one.begin()); }else{ ne = *zero.begin(); zero.erase(zero.begin()); } ans++; if(turn&1){ if(zero.count(ne))break; }else{ if(one.count(ne))break; } seen.insert(ne.second); int x = ne.second/W; int y = ne.second%W; for (int d = 0; d < 4; d++) { int xx = x + dx[d]; int yy = y + dy[d]; if(xx< 0 || xx >= H || yy < 0 || yy >= W)continue; if(seen.count(xx*W+yy))continue; if(turn&1){ one.insert({G[xx][yy], xx*W+yy}); }else{ zero.insert({G[xx][yy], xx*W+yy}); } } turn ^= 1; } cout << ans << endl; return 0; }