#include using namespace std; template using pq = priority_queue; template using pqg = priority_queue, greater>; constexpr int dx[] = {1, 0, -1, 0, 1, 1, -1, -1}; constexpr int dy[] = {0, 1, 0, -1, 1, -1, 1, -1}; void solve() { 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]; pqg> pq1, pq2; vector color(h, vector(w, -1)); pq1.push({0, 0, 0}); pq2.push({0, h - 1, w - 1}); int count = 0; while(1) { bool f = false; if((count & 1) == 0) { auto[A, i, j] = pq1.top(); pq1.pop(); if(color[i][j] != -1) continue; color[i][j] = 1; for(int r = 0; r < 4; r++) { int ii = i + dx[r], jj = j + dy[r]; if(ii < 0 || ii >= h || jj < 0 || jj >= w) continue; if(color[ii][jj] == 0) { f = true; break; }else if(color[ii][jj] == -1){ pq1.push({a[ii][jj], ii, jj}); } } }else { auto[A, i, j] = pq2.top(); pq2.pop(); if(color[i][j] != -1) continue; color[i][j] = 0; for(int r = 0; r < 4; r++) { int ii = i + dx[r], jj = j + dy[r]; if(ii < 0 || ii >= h || jj < 0 || jj > w) continue; if(color[ii][jj] == 1) { f = true; break; }else if(color[ii][jj] == -1){ pq2.push({a[ii][jj], ii, jj}); } } } count++; if(f) break; } cout << count - 2 << endl; } int main() { int T = 1; // cin >> T; while (T--) { solve(); } return 0; }