#include using namespace std; using ll = long long; const ll mod = 1e9 + 7; const int N = 200005; const int INF = 0x3f3f3f3f; struct Node { int x, y, k; }; int dis[505][505][10]; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; int main() { int n, m, k; cin >> n >> m >> k; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; int sx = -1, sy = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == 'S') { sx = i, sy = j; break; } } if (sx != -1) break; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k <= 10; k++) dis[i][j][k] = -1; } } queue q; dis[sx][sy][0] = 0; q.push({sx, sy, 0}); auto inb = [&](int r, int c) { return (0 <= r && r < n && 0 <= c && c < m); }; int ans = -1; while (!q.empty()) { Node u = q.front(); q.pop(); int d = dis[u.x][u.y][u.k]; if (a[u.x][u.y] == 'G') { ans = d; break; } for (int i = 0; i < 4; i++) { int nx = u.x + dx[i], ny = u.y + dy[i]; if (!(nx >= 0 && nx < n && ny >= 0 && ny < m)) continue; if (a[nx][ny] == '#') continue; int k = u.k; if (a[nx][ny] >= 'a' && a[nx][ny] <= 'i' && u.k != a[nx][ny] - 'a' + 1) continue; if (a[nx][ny] >= '1' && a[nx][ny] <= '9') k = a[nx][ny] - '1' + 1; if (dis[nx][ny][k] == -1) { dis[nx][ny][k] = d + 1; q.push({nx, ny, k}); } } } cout << ans << "\n"; return 0; }