#include #define fi first #define se second #define rep(i,s,n) for (int i = (s); i < (n); ++i) #define rrep(i,n,g) for (int i = (n)-1; i >= (g); --i) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define len(x) (int)(x).size() #define dup(x,y) (((x)+(y)-1)/(y)) #define pb push_back #define eb emplace_back #define Field(T) vector> using namespace std; using ll = long long; using ull = unsigned long long; template using pq = priority_queue,greater>; using P = pair; templatebool chmax(T&a,T b){if(abool chmin(T&a,T b){if(b> h >> w >> m; vector s(h); rep(i,0,h) cin >> s[i]; vector>> dist(h, vector>(w, vector(m+1, -1))); int si, sj, gi, gj; rep(i,0,h) rep(j,0,w) { if (s[i][j] == 'S') si = i, sj = j; if (s[i][j] == 'G') gi = i, gj = j; } queue> que; que.emplace(P{si, sj}, m); dist[si][sj][m] = 0; while(!que.empty()) { P p; int k; tie(p, k) = que.front(); que.pop(); int x = p.fi, y = p.se; // cout << x << " " << y << endl; rep(d,0,4) { int nx = x+dx[d], ny = y+dy[d]; if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue; if (s[nx][ny] == '#') continue; if ('a' <= s[nx][ny] && s[nx][ny] <= 'i') { if (s[nx][ny]-'a' != k) continue; if (dist[nx][ny][k] == -1) { dist[nx][ny][k] = dist[x][y][k]+1; que.emplace(P{nx, ny}, k); } } else if ('1' <= s[nx][ny] && s[nx][ny] <= '9') { int nk = s[nx][ny]-'1'; if (dist[nx][ny][nk] == -1) { dist[nx][ny][nk] = dist[x][y][k]+1; que.emplace(P{nx, ny}, nk); } } else { if (dist[nx][ny][k] == -1) { dist[nx][ny][k] = dist[x][y][k]+1; que.emplace(P{nx, ny}, k); } } } } int ans = 1000000000; rep(k,0,m+1) if (dist[gi][gj][k] != -1) ans = min(ans, dist[gi][gj][k]); if (ans == 1000000000) ans = -1; cout << ans << endl; return 0; }