#define _USE_MATH_DEFINES #include #include #include #include #include //#include #include #include #include #include #include #include ///////// #define REP(i, x, n) for(int i = x; i < n; i++) #define rep(i,n) REP(i,0,n) #define P(p) cout<<(p)< ///////// typedef long long LL; typedef long double LD; ///////// using namespace::std; ///////// int f[100][100]; bool kado(int a,int b,int c,int d){ if(d<2){ return true; } if( (c < a && a < b) || (b>W>>H; rep(i,H)rep(j,W){ cin>>f[i][j];//[y][x] } queue< vector > q; set < vector > s; vector now(5),next(5),now4(4); now[0] = 0; now[1] = 0; now[2] = -1; now[3] = -1; now[4] = 0; rep(i,4){now4[i] = now[i];} int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; q.push( now ); s.insert( now4 ); while( !q.empty()){ now = q.front();q.pop(); next[2] = f[now[1]][now[0]]; next[3] = now[2]; next[4] = now[4] + 1; rep(i,4){ next[0] = now[0] + dx[i]; next[1] = now[1] + dy[i]; if( 0 <= next[0] && next[0] < W && 0 <= next[1] && next[1] < H){ if( true == kado(f[next[1]][next[0]],next[2],next[3],next[4]) ){ if( next[0] == W-1 && next[1] == H-1){ P(next[4]); return 0; } if(next[4] <= W*H){ rep(i,4){now4[i] = next[i];} if( true == s.insert( now4 ).second ){ q.push(next); } } } } } } P(-1); return 0; }