#include using namespace std; using ll = long long; constexpr ll mod = 998244353; template struct Mint { using M=Mint; ll v; M& put(ll x) { v=(x>=1; } return res; } M inv() { return pow(mod-2); } }; using mint = Mint; int main(){ cin.tie(0); cin.sync_with_stdio(0); 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> state(h, vector(w, -1)); priority_queue, vector>, greater<>> que0, que1; que0.emplace(a[0][0], 0, 0); que1.emplace(a[h-1][w-1], h - 1, w - 1); vector dx{0, 1, 0, -1}; vector dy{1, 0, -1, 0}; int j; for(j = 0; j < h * w - 2; ++j){ if(j % 2 == 0){ while(!que0.empty()){ auto [val, x, y] = que0.top(); que0.pop(); if(state[x][y] != -1)continue; state[x][y] = 0; for(int d = 0; d < 4; ++d){ int nx = x + dx[d]; int ny = y + dy[d]; if(nx < 0 || ny < 0 || nx >= h || ny >= w)continue; if(state[nx][ny] == 0)continue; if(state[nx][ny] == 1){ cout << j - 1 << endl; exit(0); } que0.emplace(a[nx][ny], nx, ny); } break; } } else{ while(!que1.empty()){ auto [val, x, y] = que1.top(); que1.pop(); if(state[x][y] != -1)continue; state[x][y] = 1; for(int d = 0; d < 4; ++d){ int nx = x + dx[d]; int ny = y + dy[d]; if(nx < 0 || ny < 0 || nx >= h || ny >= w)continue; if(state[nx][ny] == 1)continue; if(state[nx][ny] == 0){ cout << j - 1 << endl; exit(0); } que1.emplace(a[nx][ny], nx, ny); } break; } } } }