#include using namespace std; #define rep(i, n) for(int i=0; i #include //vectorの中身を空白区切りで出力 template void print1(vector v) { for (int i = 0; i < v.size(); i++) { cout << v[i]; if (i < v.size() - 1) { cout << " "; } } } //vectorの中身を改行区切りで出力 template void print2(vector v) { for (auto x : v) { cout << x << endl; } } //二次元配列を出力 template void printvv(vector> vv) { for (vector v : vv) { print1(v); cout << endl; } } //vectorを降順にソート template void rsort(vector &v) { sort(v.begin(), v.end()); reverse(v.begin(), v.end()); } //昇順priority_queueを召喚 template struct rpriority_queue { priority_queue, greater> pq; void push(T x) { pq.push(x); } void pop() { pq.pop(); } T top() { return pq.top(); } size_t size() { return pq.size(); } bool empty() { return pq.empty(); } }; int main() { int H ,W; cin >> H >> W; vector> num(H, vector(W)); rep(i, H) { rep(j, W) { cin >> num[i][j]; } } vector> col(H, vector(W, -1)); col[0][0] = 1; col[H - 1][W - 1] = 0; map> mp; rep(i, H) { rep(j, W) { mp[num[i][j]] = { i,j }; } } set z, o; o.insert(num[1][0]); o.insert(num[0][1]); z.insert(num[H - 1][W - 2]); z.insert(num[H - 2][W - 1]); int cnt = 0; while (1) { bool ed = false; if (cnt % 2 == 0) { int n = *begin(o); int x = mp[n][0]; int y = mp[n][1]; col[x][y] = 0; if (z.count(n)) { ed = true; } else { o.erase(n); if (x > 0 && col[x - 1][y] == -1) { o.insert(num[x - 1][y]); } if (x < H - 1 && col[x+1][y]==-1) { o.insert(num[x + 1][y]); } if (y > 0 && col[x][y - 1] == -1) { o.insert(num[x][y - 1]); } if (y < W - 1 && col[x][y + 1] == -1) { o.insert(num[x][y + 1]); } } } else { int n = *begin(z); int x = mp[n][0]; int y = mp[n][1]; col[x][y] = 1; if (o.count(n)) { ed = true; } else { z.erase(n); if (x > 0 && col[x - 1][y] == -1) { z.insert(num[x - 1][y]); } if (x < H - 1 && col[x + 1][y] == -1) { z.insert(num[x + 1][y]); } if (y > 0 && col[x][y - 1] == -1) { z.insert(num[x][y - 1]); } if (y < W - 1 && col[x][y + 1] == -1) { z.insert(num[x][y + 1]); } } } cnt++; if (ed) { break; } } cout << cnt << endl; }