#include using namespace std; int dy[4] = {-1,0,1,0}; int dx[4] = {0,1,0,-1}; int n,m; int A[1001][1001]; int board[1001][1001]; int main(void) { cin.tie(0); ios::sync_with_stdio(false); cin >> n >> m; for(int i=0;i> A[i][j]; } } priority_queue >> pque[2]; memset(board,-1,sizeof(board)); pque[0].push(make_pair(-A[0][0],make_pair(0,0))); pque[1].push(make_pair(-A[n-1][m-1],make_pair(n-1,m-1))); int res = 0; while(1) { int y = pque[res%2].top().second.first; int x = pque[res%2].top().second.second; pque[res%2].pop(); //cout << res+1 << ' ' << res%2 << ' ' << y << ' ' << x << '\n'; board[y][x] = res%2; bool ok = true; for(int i=0;i<4;i++) { int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || ny >= n || nx < 0 || nx >= m) continue; if(board[ny][nx] == (1 - res%2)) { ok = false; } else if(board[ny][nx] == -1) { pque[res%2].push(make_pair(-A[ny][nx],make_pair(ny,nx))); } } if(!ok) break; res+=1; } cout << res-1 << '\n'; return 0; }