#include #define INF INT_MAX / 2 #define MOD 1000000007 using namespace std; typedef pair PI; typedef pair> PIPII; typedef long long ll; bool isKadomatsuSequence(int a2,int a1,int a0){ if(a2 == -1)return true; 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]; int w,h; int bfs(){ priority_queue>,vector>>,greater< pair> >> pq; pq.push(make_pair(0,make_pair(make_pair(0,0),-1))); while(!pq.empty()){ pair> p = pq.top();pq.pop(); int dist = p.first; int y = p.second.first.first; int x = p.second.first.second; int prev = p.second.second; if(y == h-1 && x == w-1)return dist; used[y][x] = true; //cout << y << " " << x << endl; for(int i=0;i<4;i++){ int ny = y + dy[i],nx = x + dx[i]; if(ny<0||ny>=h||nx<0||nx>=w|| !isKadomatsuSequence(prev,m[y][x],m[ny][nx]) )continue; if(used[ny][nx])continue; used[ny][nx] = true; pq.push(make_pair(dist+1,make_pair(make_pair(ny,nx),m[y][x]))); } } return -1; } int main(void) { cin >> w >> h; for(int i=0;i> m[i][j]; } } int ans = bfs(); cout << ans << endl; }