#include #include #include #include #include using namespace std; using t3i = tuple; using qt3i = queue; int main() { int n, m, k; cin >> n >> m >> k; int sx, sy, gx, gy; char s[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> s[i][j]; if (s[i][j] == 'S') { sx = i; sy = j; } else if (s[i][j] == 'G') { gx = i; gy = j; } } } int dis[n][m][k+1]; fill(dis[0][0], dis[n][0], -1); qt3i q; q.emplace(sx, sy, 0); dis[sx][sy][0] = 0; constexpr int dx[4] = {0, 1, 0, -1}; constexpr int dy[4] = {1, 0, -1, 0}; while (!q.empty()) { auto [x, y, key] = q.front(); q.pop(); for (int z = 0; z < 4; z++) { int nx = x + dx[z], ny = y + dy[z], nkey = key; if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '#') { continue; } if (isdigit(s[nx][ny])) { nkey = s[nx][ny] - '0'; } if (islower(s[nx][ny])) { if (nkey != s[nx][ny] - 'a' + 1) { continue; } } if (dis[nx][ny][nkey] == -1) { dis[nx][ny][nkey] = dis[x][y][key] + 1; q.emplace(nx, ny, nkey); } } } int ans = -1; for (int i = 0; i <= k; i++) { if (dis[gx][gy][i] != -1) { if (ans == -1 || dis[gx][gy][i] < ans) { ans = dis[gx][gy][i]; } } } cout << ans << endl; return 0; }