#ifndef ONLINE_JUDGE #define _GLIBCXX_DEBUG #endif #include #include #include using namespace std; using namespace atcoder; using ll = long long; using mint = modint998244353; //using mint = modint1000000007; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define repu(i, s, t) for (int i = (int)(s); i < (int)(t); i++) #define repd(i, s, t) for (int i = (int)(s)-1; i >= (int)(t); i--) #define all(v) v.begin(), v.end() void _u() { cerr << endl; } template void _u(H&& h, T&&... t) { cerr << h << ", "; _u(move(t)...); } #define U(...) { cerr << #__VA_ARGS__ << ": "; _u(__VA_ARGS__); } template bool chmax(T &a, const T b) { if(a >= b) return false; a = b; return true; } template bool chmin(T &a, const T b) { if(a <= b) return false; a = b; return true; } template istream& operator>>(istream &in, vector &a) { for(T &x: a) in >> x; return in; } template ostream& operator<<(ostream &out, const vector &a) { for(const T &x: a) out << x << ' '; return out; } const int di[] = {1, 0, -1, 0, 1, 1, -1, -1, 0}; const int dj[] = {0, 1, 0, -1, -1, 1, 1, -1, 0}; int main() { int h, w, m; cin >> h >> w >> m; m++; auto id = [&](int i, int j, int k) { return h*w*k + w*i + j; }; vector s(h); cin >> s; vector> g(h*w*m); rep(i, h) rep(j, w) rep(k, m) rep(t, 4) { int ni = i + di[t]; int nj = j + dj[t]; int nk = k; if(ni < 0 || ni >= h || nj < 0 || nj >= w) continue; if(s[ni][nj] == '#') continue; if(s[ni][nj] >= 'a' && s[ni][nj] <= 'z' && s[ni][nj] != 'a' + k - 1) continue; if(s[ni][nj] >= '1' && s[ni][nj] <= '9') nk = s[ni][nj] - '0'; g[id(i, j, k)].push_back(id(ni, nj, nk)); } int si, sj, gi, gj; rep(i, h) rep(j, w) { if(s[i][j] == 'S') si = i, sj = j; if(s[i][j] == 'G') gi = i, gj = j; } const int INF = 1e9; vector dist(h*w*m, INF); queue wait; dist[id(si, sj, 0)] = 0; wait.push(id(si, sj, 0)); while(!wait.empty()) { int pos = wait.front(); wait.pop(); for(int to: g[pos]) { if(dist[to] < INF) continue; dist[to] = dist[pos] + 1; wait.push(to); } } int ans = INF; rep(k, m) chmin(ans, dist[id(gi, gj, k)]); cout << (ans < INF ? ans : -1) << endl; return 0; }