#if __has_include() #include using namespace atcoder; #else #include #if __has_include() #include using namespace atcoder; #endif #endif using namespace std; #define int long long #define all(x) (x).begin(), (x).end() #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rrep(i, n) for(int i = (int)(n - 1); i >= 0; i--) template bool chmax(T &a,const T &b){if(a bool chmin(T &a,const T &b){if(a>b){a=b;return true;}return false;} // using mint = modint; signed main(){ int h, w, m; cin >> h >> w >> m; vector s(h); for(auto&& si : s) cin >> si; int si, sj, gi, gj; rep(i, h) rep(j, w){ if(s.at(i).at(j) == 'S'){ si = i; sj = j; } if(s.at(i).at(j) == 'G'){ gi = i; gj = j; } } const int inf = 1ll << 60; vector d(m + 1, vector(h, vector(w, inf))); deque> bfs; // 鍵番号、i、j、距離 d.at(0).at(si).at(sj) = 0; bfs.emplace_back(0, si, sj, 0); while(!bfs.empty()){ auto [fkey, fi, fj, fd] = bfs.front(); bfs.pop_front(); for(auto [di, dj] : vector>{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}){ int tkey = fkey, ti = fi + di, tj = fj + dj, td = fd + 1; if(ti < 0 || ti >= h || tj < 0 || tj >= w) continue; if(s.at(ti).at(tj) == '#') continue; if(islower(s.at(ti).at(tj)) && fkey != s.at(ti).at(tj) - 'a' + 1) continue; if(isdigit(s.at(ti).at(tj))) tkey = s.at(ti).at(tj) - '0'; if(d.at(tkey).at(ti).at(tj) != inf) continue; d.at(tkey).at(ti).at(tj) = td; bfs.emplace_back(tkey, ti, tj, td); } } int ans = inf; rep(i, m + 1) chmin(ans, d.at(i).at(gi).at(gj)); cout << (ans == inf ? -1ll : ans) << '\n'; }