#include using namespace std; using ll = long long; template using pq = priority_queue, greater>; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int main(){ cin.tie(nullptr); ios_base::sync_with_stdio(false); int H, W, ans=0, x, y, cnt=0, a, xx, yy; cin >> H >> W; vector used(H, vector(W, -1)); pq> que0, que1; vector A(H, vector(W)); for (int i=0; i> A[i][j]; } used[0][0] = 1; used[H-1][W-1] = 0; auto check=[&](int i, int j)->bool{ return 0 <= i & i < H & 0 <= j & j < W; }; for (int i=0; i<4; i++){ x = dx[i]; y = dy[i]; if (check(x, y)){ que1.push({A[x][y], x, y}); } } for (int i=0; i<4; i++){ x = dx[i]+H-1; y = dy[i]+W-1; if (check(x, y)){ que0.push({A[x][y], x, y}); } } while(1){ cnt++; cnt %= 2; if (cnt == 1){ while(!que1.empty()){ tie(a, x, y) = que1.top(); que1.pop(); if (used[x][y] == -1){ used[x][y] = 1; ans++; for (int j=0; j<4; j++){ xx = x+dx[j]; yy = y+dy[j]; if (check(xx, yy)){ if (used[xx][yy] == 0){ cout << ans << endl; return 0; } else if (used[xx][yy] == -1){ que1.push({A[xx][yy], xx, yy}); } } } break; } } } else{ while(!que0.empty()){ tie(a, x, y) = que0.top(); que0.pop(); if (used[x][y] == -1){ used[x][y] = 0; ans++; for (int j=0; j<4; j++){ xx = x+dx[j]; yy = y+dy[j]; if (check(xx, yy)){ if (used[xx][yy] == 1){ cout << ans << endl; return 0; } else if (used[xx][yy] == -1){ que0.push({A[xx][yy], xx, yy}); } } } break; } } } } cout << ans << endl; return 0; }