#include #include using namespace std; template class y_combinator { F f; public: y_combinator(F&& f) : f(std::forward(f)) {} template auto operator()(Args&&... args) const { return f(*this, std::forward(args)...); } }; using ll = long long; using ld = long double; template > using prique = std::priority_queue, U>; template T floor(T a, T b) noexcept { return a / b - (a % b && (a ^ b) < 0); } template T ceil(T a, T b) noexcept { return floor(a + b - 1, b); } template bool chmin(T& x, const T& y) noexcept { return (x > y ? x = y, true : false); } template bool chmax(T& x, const T& y) noexcept { return (x < y ? x = y, true : false); } #define overload4(a, b, c, d, e, ...) e #define rep1(a) for (long long _i = 0; _i < (a); _i++) #define rep2(i, a) for (long long i = 0; i < (a); i++) #define rep3(i, a, b) for (long long i = (a); i < (b); i++) #define rep4(i, a, b, c) for (long long i = (a); i < (b); i += (c)) #define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__) #define rrep(i, a, b, c) for (long long i = (a); i > (b); i += (c)) #define all(x) std::begin(x), std::end(x) #define rall(x) std::rbegin(x), std::rend(x) #define pb push_back #ifndef LOCAL #define debug(...) #endif void run_case() { int H, W, M; cin >> H >> W >> M; vector S(H); rep(i, H) cin >> S[i]; vector dp(H, vector(W, vector(M + 1, 1e9))); auto find = [&](char s) -> pair { rep(i, H) rep(j, W) if (S[i][j] == s) { return {i, j}; } assert(0); }; auto st = find('S'); auto go = find('G'); dp[st.first][st.second][0] = 0; queue> que; que.push({st.first, st.second, 0}); const int dx[] = {0, 1, 0, -1, 0}; while (!que.empty()) { auto [i, j, k] = que.front(); que.pop(); rep(r, 4) { int ni = i + dx[r], nj = j + dx[r + 1]; if (ni < 0 || nj < 0 || ni >= H || nj >= W) continue; if (S[ni][nj] == '#') continue; if ('a' <= S[ni][nj] && S[ni][nj] <= 'i') { if (S[ni][nj] - 'a' + 1 != k) continue; if (chmin(dp[ni][nj][k], dp[i][j][k] + 1)) { que.push({ni, nj, k}); } } else if ('1' <= S[ni][nj] && S[ni][nj] <= '9') { int ch = S[ni][nj] - '0'; if (chmin(dp[ni][nj][ch], dp[i][j][k] + 1)) { que.push({ni, nj, ch}); } } else { if (chmin(dp[ni][nj][k], dp[i][j][k] + 1)) { que.push({ni, nj, k}); } } } } int ans = 1e9; rep(i, M + 1) { // cout << "i = " << i << endl; chmin(ans, dp[go.first][go.second][i]); // rep(j, H) rep(k, W) cout << dp[j][k][i] << " \n"[k == W - 1]; } cout << (ans == 1e9 ? -1 : ans) << "\n"; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::fixed(std::cout).precision(16); int T = 1; // cin >> T; while (T--) run_case(); return 0; }