#include using namespace std; #define For(i, a, b) for(int i = (a); i < (b); i++) #define rep(i, n) For(i, 0, n) #define rFor(i, a, b) for(int i = (a); i >= (b); i--) #define ALL(v) (v).begin(), (v).end() #define rALL(v) (v).rbegin(), (v).rend() #define SZ(v) ((int)(v).size()) using lint = long long; using ld = long double; int INF = 2000000000; lint LINF = 1000000000000000000; struct SetupIo { SetupIo() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(15); cerr << fixed << setprecision(15); } } setupio; // a <- max(a, b) template bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } // a <- min(a, b) template bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; } vector di = {0, 0, -1, 1}; vector dj = {-1, 1, 0, 0}; int main() { int H, W, M; cin >> H >> W >> M; vector> S(H, vector(W)); int si, sj, gi, gj; rep(i, H) { rep(j, W) { cin >> S[i][j]; if (S[i][j] == 'S') { si = i; sj = j; } if (S[i][j] == 'G') { gi = i; gj = j; } } } auto inside = [&](int i, int j) -> bool { return (0 <= i && i < H && 0 <= j && j < W); }; // dist[i][j][k]:= 鍵 k を持った状態で (i, j) に到達 vector>> dist(H, vector>(W, vector(M + 1, INF))); queue> q; dist[si][sj][0] = 0; q.emplace(si, sj, 0); while (!q.empty()) { auto [i, j, k] = q.front(); q.pop(); rep(kk, 4) { int ni = i + di[kk], nj = j + dj[kk]; if (!inside(ni, nj) || S[ni][nj] == '#') { continue; } if (S[ni][nj] == '.' || S[ni][nj] == 'S' || S[ni][nj] == 'G') { int nk = k; if (chmin(dist[ni][nj][nk], dist[i][j][k] + 1)) { q.emplace(ni, nj, nk); } } else if ('1' <= S[ni][nj] && S[ni][nj] <= '9') { int nk = S[ni][nj] - '0'; if (chmin(dist[ni][nj][nk], dist[i][j][k] + 1)) { q.emplace(ni, nj, nk); } } else { int x = S[ni][nj] - 'a' + 1; if (k == x) { int nk = k; if (chmin(dist[ni][nj][nk], dist[i][j][k] + 1)) { q.emplace(ni, nj, nk); } } } } } int ans = INF; rep(k, M + 1) { chmin(ans, dist[gi][gj][k]); } cout << (ans != INF ? ans : -1) << "\n"; }