#ifndef MY_HEADER #define MY_HEADER #include #include using namespace std; using namespace atcoder; using lint = long long; using ulint = unsigned long long; using llint = __int128_t; struct edge; using graph = vector>; #define endl '\n' constexpr int INF = 1<<30; constexpr lint INF64 = 1LL<<61; constexpr lint mod107 = 1e9+7; using mint107 = modint1000000007; constexpr long mod = 998244353; using mint = modint998244353; lint ceilDiv(lint x, lint y){if(x >= 0){return (x+y-1)/y;}else{return x/y;}} lint floorDiv(lint x, lint y){if(x >= 0){return x/y;}else{return (x-y+1)/y;}} lint Sqrt(lint x) {assert(x >= 0); lint ans = sqrt(x); while(ans*ans > x)ans--; while((ans+1)*(ans+1)<=x)ans++; return ans;} lint gcd(lint a,lint b){if(a 0){int a = n%10;char b = '0' + a;string c = "";c += b;n /= 10;ans = c + ans;}}return ans;} string toString(lint n, lint k){string ans = toString(n);string tmp = "";while(ans.length() + tmp.length() < k){tmp += "0";}return tmp + ans;} vectorprime;void makePrime(lint n){prime.push_back(2);for(lint i=3;i<=n;i+=2){bool chk = true;for(lint j=0;j= 0; i--) #define vec vector #define pb push_back #define eb emplace_back #define se second #define fi first #define al(x) x.begin(),x.end() #define ral(x) x.rbegin(),x.rend() struct edge{ edge(lint v, lint c = 1) {to = v, cost = c;} lint to; lint cost; }; #endif int main(){ lint H, W, M; cin >> H >> W >> M; vec>S(H+2, vec(W+2, '#')); int sx,sy,gx,gy; rep(i, H) { rep(j, W) { char c;cin >> c; S[i+1][j+1] = c; if(c == 'S'){ sx = i+1; sy = j+1; } if(c == 'G') { gx = i+1; gy = j+1; } } } vecdx = {0,0,1,-1}; vecdy = {1,-1,0,0}; vec dp(H+1, vec(W+1, vec(M+1, INF64))); dp[sx][sy][0] = 0; queue> que; que.push({sx,sy,0}); while(!que.empty()) { auto v = que.front(); que.pop(); int x = v[0]; int y = v[1]; int k = v[2]; rep(d, 4) { int nx = x + dx[d]; int ny = y + dy[d]; if(S[nx][ny] == '#') continue; else if(S[nx][ny] >= 'a' && S[nx][ny ] <= 'z') { if(k != S[nx][ny]-'a'+1) continue; if(dp[nx][ny][k] > dp[x][y][k] + 1) { dp[nx][ny][k] = dp[x][y][k] + 1; que.push({nx,ny,k}); } } else if(S[nx][ny] >= '0' && S[nx][ny ] <= '9') { int nk = S[nx][ny] - '0'; if(dp[nx][ny][nk] > dp[x][y][k] + 1) { dp[nx][ny][nk] = dp[x][y][k] + 1; que.push({nx,ny,nk}); } } else{ if(dp[nx][ny][k] > dp[x][y][k] + 1) { dp[nx][ny][k] = dp[x][y][k] + 1; que.push({nx,ny,k}); } } } } lint ans = INF64; rep(i, M+1) ans = min(ans, dp[gx][gy][i]); if(ans == INF64) ans = -1; cout << ans << endl; }