// #pragma GCC target("avx2") // #pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") #include using namespace std; using uint = unsigned int; using ll = long long; using ull = unsigned long long; using ld = long double; template using V = vector; template using VV = V>; template using VVV = V>; template using VVVV = VV>; #define rep(i,n) for(ll i=0ll;(i)<(n);(i)++) #define REP(i,a,n) for(ll i=(a);(i)<(n);(i)++) #define rrep(i,n) for(ll i=(n)-1;(i)>=(0ll);(i)--) #define RREP(i,a,n) for(ll i=(n)-1;(i)>=(a);(i)--) const long long INF = (1LL << 60); const long long mod99 = 998244353; const long long mod107 = 1000000007; const long long mod = mod99; #define eb emplace_back #define be(v) (v).begin(),(v).end() #define all(v) (v).begin(),(v).end() #define foa(i,v) for(auto& (i) : (v)) #define UQ(v) sort(be(v)), (v).erase(unique(be(v)), (v).end()) #define UQ2(v,cmp) sort(be(v)), (v).erase(unique(be(v),cmp), (v).end()) #define UQ3(v,cmp) sort(be(v),cmp), (v).erase(unique(be(v)), (v).end()) #define UQ4(v,cmp,cmp2) sort(be(v), cmp), (v).erase(unique(be(v),cmp2), (v).end()) #define LB(x,v) (lower_bound(be(v),(x))-(v).begin()) #define LB2(x,v,cmp) (lower_bound(be(v),(x),(cmp))-(v).begin()) #define UB(x,v) (upper_bound(be(v),(x))-(v).begin()) #define UB2(x,v,cmp) (upper_bound(be(v),(x),(cmp))-(v).begin()) #define dout() cout << fixed << setprecision(20) #define randinit() srand((unsigned)time(NULL)) template bool chmin(T& t, const U& u) { if (t > u){ t = u; return 1;} return 0; } template bool chmax(T& t, const U& u) { if (t < u){ t = u; return 1;} return 0; } ll Rnd(ll L=0, ll R=mod99){return rand()%(R-L)+L;} void solve(){ ll h,w,m; cin >> h >> w >> m; V v(h); rep(i,h) cin >> v[i]; VVV dist(m+1, VV(h, V(w, INF))); queue> que; ll gx, gy; rep(i, h) rep(j, w){ if(v[i][j] == 'S'){ que.push({0, i, j}); dist[0][i][j] = 0; } if(v[i][j] == 'G'){ gx = i, gy = j; } } V dx={0,1,0,-1}, dy={1,0,-1,0}; while(!que.empty()){ auto[a,x,y] = que.front(); que.pop(); if(v[x][y] == '#') continue; if('1' <= v[x][y] and v[x][y] <= '9' and v[x][y] - '0' != a){ if(chmin(dist[v[x][y]-'0'][x][y], dist[a][x][y])){ que.push({v[x][y] - '0', x, y}); } continue; } rep(i, 4){ ll nx = x+dx[i]; ll ny = y+dy[i]; if(nx < 0 or ny < 0 or nx >= h or ny >= w) continue; if(v[nx][ny] == '#') continue; if('a' <= v[x][y] and v[x][y] <= 'i' and v[x][y] - 'a' != a-1) continue; if(chmin(dist[a][nx][ny], dist[a][x][y]+1)) que.push({a, nx, ny}); } } ll ans = INF; rep(i, m+1) chmin(ans, dist[i][gx][gy]); if(ans == INF) ans = -1; cout << ans << endl; } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int t=1; // cin >> t; rep(i,t) solve(); }