#include #include #define rep(i,n) for(int i=0;i vi; typedef vector vl; typedef vector> vvi; typedef vector> vvl; typedef long double ld; typedef pair P; ostream& operator<<(ostream& os, const modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const static_modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const dynamic_modint& a) {os << a.val(); return os;} template istream& operator>>(istream& is, vector& v){int n = v.size(); assert(n > 0); rep(i, n) is >> v[i]; return is;} template ostream& operator<<(ostream& os, const pair& p){os << p.first << ' ' << p.second; return os;} template ostream& operator<<(ostream& os, const vector& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : " "); return os;} template ostream& operator<<(ostream& os, const vector>& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : ""); return os;} template void chmin(T& a, T b){a = min(a, b);} template void chmax(T& a, T b){a = max(a, b);} int main(){ int h, w; cin >> h >> w; vector> a(h, vector(w)); cin >> a; using PQ = priority_queue, greater

>; PQ pq0; PQ pq1; pq0.emplace(0, 0); pq1.emplace(0, h * w - 1); int ans = -2; bool stop_flag = false; vector dy = {1, 0, -1, 0}; vector dx = {0, 1, 0, -1}; vector> col(h, vector(w, -1)); auto paint = [&](PQ& pq, int c){ int tile = -1; int fy = -1; int fx = -1; while(true){ auto p = pq.top(); pq.pop(); tile = p.second; fy = tile / w; fx = tile % w; if(col[fy][fx] == -1) break; } col[fy][fx] = c; rep(t, 4){ int ty = fy + dy[t]; int tx = fx + dx[t]; if(ty >= 0 and ty < h and tx >= 0 and tx < w){ if(col[ty][tx] == -1){ pq.emplace(a[ty][tx], ty * w + tx); }else{ if(col[ty][tx] != c) stop_flag = true; } } } ans++; }; while(true){ paint(pq0, 0); if(stop_flag) break; paint(pq1, 1); if(stop_flag) break; } cout << ans << "\n"; return 0; }