#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int dy[] = {-1, 1, 0, 0}; int dx[] = {0, 0, 1, -1}; int main() { int w, h; cin >> w >> h; vector > m(h+2, vector(w+2, -1)); for(int y=1; y<=h; ++y){ for(int x=1; x<=w; ++x){ cin >> m[y][x]; } } vector > > > check(h+2, vector > >(w+2, vector >(10, vector(10, false)))); queue > q; check[1][1][0][m[1][1]] = 1; q.push(make_tuple(1, 1, 0, m[1][1])); int ret = 0; while(!q.empty()){ int n = q.size(); while(--n >= 0){ int y, x, a, b; tie(y, x, a, b) = q.front(); q.pop(); if(y == h && x == w){ cout << ret << endl; return 0; } for(int i=0; i<4; ++i){ int y2 = y + dy[i]; int x2 = x + dx[i]; int c = m[y2][x2]; if(c == -1) continue; if(a != 0 && !(a < b && b > c) && !(a > b && b < c)) continue; if(!check[y2][x2][b][c]){ check[y2][x2][b][c] = true; q.push(make_tuple(y2,x2, b, c)); } } } ++ ret; } cout << -1 << endl; return 0; }