#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; vector> A(h, vector(w)), B(h, vector(w, -1)); for(auto &&vec : A){ for(auto &&v : vec) cin >> v; } A[0][0] = A[h - 1][w - 1] = 1; priority_queue, vector>, greater>> pq1, pq2; pq1.emplace(0, 0, 0); pq2.emplace(0, h - 1, w - 1); B[0][0] = 0; B[h - 1][w - 1] = 1; for(int i = 0; i < h * w; i++){ int s = i % 2; auto [v, y, x] = (s == 0 ? pq1.top() : pq2.top()); (s == 0 ? pq1.pop() : pq2.pop()); B[y][x] = s; for(int j = 0; j < 4; j++){ int ny = y + (j == 0) - (j == 1); int nx = x + (j == 2) - (j == 3); if(ny < 0 || nx < 0 || ny >= h || nx >= w) continue; if(B[ny][nx] >= 0 && B[ny][nx] != s){ cout << i + 1 - 2 << '\n'; return 0; } if((-B[ny][nx] - 1) >> s & 1) continue; B[ny][nx] -= 1 << s; if(s == 0){ pq1.emplace(A[ny][nx], ny, nx); }else{ pq2.emplace(A[ny][nx], ny, nx); } } } }