using System; using static System.Console; using System.Linq; using System.Collections.Generic; class Program { static int NN => int.Parse(ReadLine()); static long[] NList => ReadLine().Split().Select(long.Parse).ToArray(); static long[][] NArr(long n) => Enumerable.Repeat(0, (int)n).Select(_ => NList).ToArray(); static string[] SList(long n) => Enumerable.Repeat(0, (int)n).Select(_ => ReadLine()).ToArray(); public static void Main() { Solve(); } static void Solve() { var c = NList; var (h, w, m) = (c[0], c[1], c[2]); var s = SList(h); var (sx, sy, gx, gy) = (0, 0, 0, 0); for (var i = 0; i < h; ++i) for (var j = 0; j < w; ++j) { if (s[i][j] == 'S') { sx = i; sy = j; } else if (s[i][j] == 'G') { gx = i; gy = j; } } var dp = new int[h, w, m + 1]; var INF = int.MaxValue / 2; for (var i = 0; i < h; ++i) for (var j = 0; j < w; ++j) for (var k = 0; k <= m; ++k) dp[i, j, k] = INF; var mx = new int[] { 0, 0, -1, 1 }; var my = new int[] { -1, 1, 0, 0 }; var q = new Queue<(int x, int y, int k)>(); q.Enqueue((sx, sy, 0)); dp[sx, sy, 0] = 0; while (q.Count > 0) { var cur = q.Dequeue(); if (cur.x == gx && cur.y == gy) { WriteLine(dp[cur.x, cur.y, cur.k]); return; } for (var i = 0; i < 4; ++i) { var nx = cur.x + mx[i]; var ny = cur.y + my[i]; if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue; var nk = cur.k; if (s[nx][ny] >= '1' && s[nx][ny] <= '9') { nk = s[nx][ny] - '0'; } if (s[nx][ny] == '#' || (s[nx][ny] >= 'a' && s[nx][ny] <= 'i' && nk != s[nx][ny] - 'a' + 1)) continue; if (dp[nx, ny, nk] <= dp[cur.x, cur.y, cur.k] + 1) continue; dp[nx, ny, nk] = dp[cur.x, cur.y, cur.k] + 1; q.Enqueue((nx, ny, nk)); } } WriteLine("-1"); } }