#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(); //cout<h||ny<0||ny>=w) continue; int cur = G[x][y]; int next = G[nx][ny]; if(precur&&cur>next)continue; if(cur!=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]; for(int i = 0;i<10;i++){ ans = min(dist[h-1][w-1][i],ans); } if(ans==1000'000'000)ans= -1; cout<> h >> w; for(int i = 0;i> G[i][j]; } solve(); }