#if __INCLUDE_LEVEL__ == 0 #include __BASE_FILE__ namespace { void solve() { int h, w; scan(h, w); std::vector a(h, std::vector(w)); scan(a); std::vector color(h, std::vector(w, -1)); std::array>, 2> q; const auto push = [&](int t, int i, int j) { if (color[i][j] == -1) { q[t].emplace(-a[i][j], i, j); } }; push(1, 0, 0); push(0, h - 1, w - 1); int ans = 0; for (int t = 1;;) { const auto [_, i, j] = q[t].top(); q[t].pop(); if (color[i][j] == -1) { color[i][j] = t; } else { continue; } ++ans; for (auto [ni, nj] : {std::pair{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) { ni += i; nj += j; if (0 <= ni && ni < h && 0 <= nj && nj < w) { if (color[ni][nj] == (t ^ 1)) { print(ans - 2); return; } push(t, ni, nj); } } t ^= 1; } } } // namespace int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout << std::setprecision(DBL_DECIMAL_DIG); solve(); } #else // __INCLUDE_LEVEL__ #include template bool chmin(T& x, U&& y) { return y < x && (x = std::forward(y), true); } template bool chmax(T& x, U&& y) { return x < y && (x = std::forward(y), true); } template T inf() { T ret; std::memset(&ret, 0x3f, sizeof(ret)); return ret; } template T inf() { return std::numeric_limits::infinity(); } template concept Range = std::ranges::range && !std::convertible_to; template concept Tuple = std::__is_tuple_like::value && !Range; namespace std { istream& operator>>(istream& is, Range auto&& r) { for (auto&& e : r) { is >> e; } return is; } istream& operator>>(istream& is, Tuple auto&& t) { return apply([&](auto&... xs) -> istream& { return (is >> ... >> xs); }, t); } ostream& operator<<(ostream& os, Range auto&& r) { for (string_view sep = ""; auto&& e : r) { os << exchange(sep, " ") << e; } return os; } ostream& operator<<(ostream& os, Tuple auto&& t) { const auto f = [&](auto&... xs) -> ostream& { [[maybe_unused]] string_view sep = ""; ((os << exchange(sep, " ") << xs), ...); return os; }; return apply(f, t); } } // namespace std void scan(auto&&... xs) { std::cin >> std::tie(xs...); } void print(auto&&... xs) { std::cout << std::tie(xs...) << '\n'; } template class fix { public: explicit fix(F f) : f_(std::move(f)) {} decltype(auto) operator()(auto&&... xs) const { return f_(std::ref(*this), std::forward(xs)...); } private: F f_; }; inline auto rep(int l, int r) { return std::views::iota(std::min(l, r), r); } inline auto rep(int n) { return rep(0, n); } inline auto rep1(int l, int r) { return rep(l, r + 1); } inline auto rep1(int n) { return rep(1, n + 1); } using namespace std::literals; namespace ranges = std::ranges; namespace views = std::views; using i64 = std::int64_t; #endif // __INCLUDE_LEVEL__