#include using namespace std; #define rep(i,n) for(int i=0;ib&&c>b) return true; return false; } int main(){ int w,h; cin>>w>>h; int m[h][w]; rep(i,h) rep(j,w) cin>>m[i][j]; rep(i,4) rep(j,h) rep(k,w) bfs[i][j][k]=1<<30; bfs[0][0][1]=1; bfs[2][1][0]=1; int mx[]={1,0,0,-1}; int my[]={0,-1,1,0}; queue> q; q.push(make_tuple(0,1,0)); q.push(make_tuple(1,0,2)); while(!q.empty()){ auto crt=q.front(); q.pop(); int y=get<0>(crt); int x=get<1>(crt); int from=get<2>(crt); rep(i,4){ if((from^3)==i) continue; if(0>y+my[i]||y+my[i]>=h||0>x+mx[i]||x+mx[i]>=w) continue; if(ok(m[y-my[from]][x-mx[from]],m[y][x],m[y+my[i]][x+mx[i]])){ bfs[i][y+my[i]][x+mx[i]]=bfs[from][y][x]+1; q.push(make_tuple(y+my[i],x+mx[i],i)); } } rep(i,4){ if(bfs[i][h-1][w-1]!=1<<30){ cout<