#include #define INF INT_MAX / 2 #define MOD 1000000007 using namespace std; typedef pair PII; typedef pair> PIPII; typedef long long ll; bool isKadomatsuSequence(int a2,int a1,int a0){ if((a1 < a0 && a1 < a2 || a1 > a2 && a1 > a0) && a2 != a0)return true; return false; } int dy[] = {0,1,0,-1}; int dx[] = {1,0,-1,0}; int m[101][101]; bool used[101][101][11][11]; int memo[101][101][11][11]; int w,h; int dfs(int y,int x,int prev2,int prev1){ if(y<0||y>=h||x<0||x>=w|| prev2 != -1 && !isKadomatsuSequence(prev2,prev1,m[y][x]) || used[y][x][prev2+1][prev1+1])return INF; if(y == h-1 && x == w-1)return 0; if(memo[y][x][prev2+1][prev1+1] != -1)return memo[y][x][prev2+1][prev1+1]; //cout << y << " " << x << endl; int ret = INF; for(int i=0;i<4;i++){ used[y][x][prev2+1][prev1+1] = true; ret = min(ret,dfs(y+dy[i],x+dx[i],prev1,m[y][x])); used[y][x][prev2+1][prev1+1] = false; } return memo[y][x][prev2+1][prev1+1] = ret+1; } int main(void) { cin >> w >> h; memset(memo,-1,sizeof(memo)); for(int i=0;i> m[i][j]; } } int ans = dfs(0,0,-1,-1); if(ans>=INF)cout << -1 << endl; else cout << ans << endl; }