#include using namespace std; #define CPP_STR(x) CPP_STR_I(x) #define CPP_CAT(x, y) CPP_CAT_I(x, y) #define CPP_STR_I(args...) #args #define CPP_CAT_I(x, y) x##y #define ASSERT(expr...) assert((expr)) using i8 = int8_t; using u8 = uint8_t; using i16 = int16_t; using u16 = uint16_t; using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; using f32 = float; using f64 = double; // }}} constexpr i64 INF = 1'010'000'000'000'000'017LL; constexpr i64 MOD = 998244353LL; constexpr f64 EPS = 1e-12; constexpr f64 PI = 3.14159265358979323846; #define M5 100007 #define M9 1000000000 #define F first #define S second // util {{{ #define FOR(i, start, end) for (i64 i = (start), CPP_CAT(i, xxxx_end) = (end); i < CPP_CAT(i, xxxx_end); ++i) #define REP(i, n) FOR(i, 0, n) #define all(x) (x).begin(), (x).end() #define ll long long int #define VI vector #define VVI vector #define ISD true #define debug(x) \ if (ISD) \ cout << #x << ": " << x << endl template > bool chmax(T &xmax, const U &x, Comp comp = {}) { if (comp(xmax, x)) { xmax = x; return true; } return false; } template > bool chmin(T &xmin, const U &x, Comp comp = {}) { if (comp(x, xmin)) { xmin = x; return true; } return false; } int main() { int H, W; cin >> H >> W; vector> A(H, vector(W)); REP(i, H) REP(j, W) cin >> A[i][j]; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int x[2], y[2]; x[1] = 0; x[0] = H - 1; y[1] = 0; y[0] = W - 1; using P = pair>; priority_queue, greater

> q[2]; q[1].push({0, {0, 0}}); q[0].push({0, {H - 1, W - 1}}); set> s[2]; s[1].insert({0, 0}); s[0].insert({H - 1, W - 1}); ll ans = 1; while (1) { P t = q[ans % 2].top(); q[ans % 2].pop(); int cx = t.S.F; int cy = t.S.S; if (s[!(ans % 2)].count({cx, cy}) == 1) { cout << ans - 2 << endl; return 0; } REP(i, 4) { int nx = cx + dx[i]; int ny = cy + dy[i]; if (nx < 0 || nx >= H || ny < 0 || ny >= W || s[ans % 2].count({nx, ny}) == 1) { continue; } q[ans % 2].push({A[nx][ny], {nx, ny}}); s[ans % 2].insert({nx, ny}); } ans++; } }