#include using namespace std; typedef pair pii; typedef long long ll; const int N = 2000086, MOD = 998244353, INF = 0x3f3f3f3f; ll res; int n, m, cnt, w[N]; char s[508][508]; int d[508][508][10], k; int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; int main() { cin >> n >> m >> k; for (int i = 1; i < n + 1; i++) scanf("%s", s[i] + 1); memset(d, 0x3f, sizeof d); queue > q; for (int i = 1; i < n + 1; i++) for (int j = 1; j < m + 1; j++) if (s[i][j] == 'S') d[i][j][0] = 0, q.push({i, j, 0}); while (q.size()) { auto u = q.front(); q.pop(); int x = u[0], y = u[1], p = u[2]; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (!nx || !ny || nx > n || ny > m || s[nx][ny] == '#') continue; if (s[nx][ny] == 'G') { printf("%d\n", d[x][y][p] + 1); return 0; } if (s[nx][ny] >= '1' && s[nx][ny] <= '9') { if (d[nx][ny][s[nx][ny] - '0'] == INF) { d[nx][ny][s[nx][ny] - '0'] = d[x][y][p] + 1; q.push({nx, ny, s[nx][ny] - '0'}); } } else if (s[nx][ny] >= 'a' && s[nx][ny] <= 'i') { if (p == s[nx][ny] - 'a' + 1 && d[nx][ny][s[nx][ny] - 'a' + 1] == INF) { d[nx][ny][s[nx][ny] - 'a' + 1] = d[x][y][p] + 1; q.push({nx, ny, s[nx][ny] - 'a' + 1}); } } else { if (d[nx][ny][p] == INF) { d[nx][ny][p] = d[x][y][p] + 1; q.push({nx, ny, p}); } } } } puts("-1"); return 0; }