#include #include using namespace std; using namespace atcoder; istream &operator>>(istream &is, modint &a) { long long v; is >> v; a = v; return is; } ostream &operator<<(ostream &os, const modint &a) { return os << a.val(); } istream &operator>>(istream &is, modint998244353 &a) { long long v; is >> v; a = v; return is; } ostream &operator<<(ostream &os, const modint998244353 &a) { return os << a.val(); } istream &operator>>(istream &is, modint1000000007 &a) { long long v; is >> v; a = v; return is; } ostream &operator<<(ostream &os, const modint1000000007 &a) { return os << a.val(); } typedef long long ll; typedef vector> Graph; typedef pair pii; typedef pair pll; #define FOR(i,l,r) for (int i = l;i < (int)(r); i++) #define rep(i,n) for (int i = 0;i < (int)(n); i++) #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define my_sort(x) sort(x.begin(), x.end()) #define my_max(x) *max_element(all(x)) #define my_min(x) *min_element(all(x)) template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } const int INF = (1<<30) - 1; const ll LINF = (1LL<<62) - 1; const int MOD = 998244353; const int MOD2 = 1e9+7; const double PI = acos(-1); vector di = {1,0,-1,0}; vector dj = {0,1,0,-1}; #ifdef LOCAL # include # define debug(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__) #else # define debug(...) (static_cast(0)) #endif int main(){ cin.tie(0); ios_base::sync_with_stdio(false); int H, W; cin >> H >> W; vector A(H, vector(W)); rep(i,H)rep(j,W) cin >> A[i][j]; vector color(H, vector(W, -1)); color[0][0] = 1; color[H - 1][W - 1] = 0; using P = tuple; //(val, i, j) priority_queue, greater

> pq1, pq0; rep(d,4){ int ni = 0 + di[d], nj = 0 + dj[d]; if(ni < 0 || ni >= H || nj < 0 || nj >= W) continue; if(color[ni][nj] != -1) continue; pq1.push(P{A[ni][nj], ni, nj}); } rep(d,4){ int ni = H - 1 + di[d], nj = W - 1 + dj[d]; if(ni < 0 || ni >= H || nj < 0 || nj >= W) continue; if(color[ni][nj] != -1) continue; pq0.push(P{A[ni][nj], ni, nj}); } int t = 0; bool isFin = false; while(true){ debug(pq1, pq0, color, t); if(t % 2 == 0){ // 色1を塗る while(true){ if(pq1.empty()){ cout << t << endl; return 0; } auto [val, i, j] = pq1.top(); pq1.pop(); if(color[i][j] != -1) continue; color[i][j] = 1; rep(d,4){ int ni = i + di[d], nj = j + dj[d]; if(ni < 0 || ni >= H || nj < 0 || nj >= W) continue; if(color[ni][nj] == 0) isFin = true; if(color[ni][nj] != -1) continue; pq1.push(P{A[ni][nj], ni, nj}); } break; } } else{ while(true){ if(pq0.empty()){ cout << t << endl; return 0; } auto [val, i, j] = pq0.top(); pq0.pop(); if(color[i][j] != -1) continue; color[i][j] = 0; rep(d,4){ int ni = i + di[d], nj = j + dj[d]; if(ni < 0 || ni >= H || nj < 0 || nj >= W) continue; if(color[ni][nj] == 1) isFin = true; if(color[ni][nj] != -1) continue; pq0.push(P{A[ni][nj], ni, nj}); } break; } } t++; if(isFin) break; } cout << t << endl; }