#include using namespace std; #include using namespace atcoder; using ll = long long; int h,w; int G[100][100]; int dist[100][100][10]; using TUP = tuple; void solve(){ for(int i = 0;i<100;i++){ for(int j = 0;j<100;j++){ for(int k = 0;k<10;k++)dist[i][j][k] = 1000'000'000; } } queue Q; dist[0][0][G[0][0]] = 0; Q.emplace(0,0,G[0][0]); int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1}; while(Q.size()){ auto [x,y,pre] = Q.front(); int cur_dist = dist[x][y][pre]; Q.pop(); for(int i = 0;i<4;i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx<0||nx>=h||ny<0||ny>=w) continue; int cur = G[x][y]; int next = G[nx][ny]; if(precur&&cur>next)continue; if(cur!=next&&pre!=next){ if(dist[nx][ny][cur]>cur_dist+1){ dist[nx][ny][cur] = cur_dist + 1; Q.emplace(nx,ny,cur); } } } } int ans = dist[h-1][w-1][0]; /* cout<> h >> w; swap(h,w); for(int i = 0;i> G[i][j]; } solve(); }