from copy import deepcopy from collections import deque H, W, M = map(int, input().split()) A = [[]] alpha_num = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9} num_set = set("123456789") for row in range(H): inp = list(input()) for col in range(W): if inp[col] in alpha_num: inp[col] = alpha_num[inp[col]] elif inp[col] in num_set: inp[col] = int(inp[col]) + 10 elif inp[col] == "S": s_row, s_col = row, col inp[col] = "." elif inp[col] == "G": g_row, g_col = row, col A[0].append(inp) for _ in range(M): A.append(deepcopy(A[-1])) vid_cost = [None for _ in range(H*W*(M+1))] s_vid = W*s_row + s_col vid_cost[s_vid] = 0 dif_rows = [-1, 1, 0, 0] dif_cols = [0, 0, -1, 1] q = deque() q.append((0, s_row, s_col)) while q: dim, now_row, now_col = q.popleft() now_vid = dim*H*W + W*now_row + now_col for dif_row, dif_col in zip(dif_rows, dif_cols): ne_row = now_row + dif_row ne_col = now_col + dif_col if 0 <= ne_row < H and 0 <= ne_col < W: if A[dim][ne_row][ne_col] == "#": continue elif A[dim][ne_row][ne_col] == ".": ne_vid = dim*H*W + W*ne_row + ne_col if vid_cost[ne_vid] == None: vid_cost[ne_vid] = vid_cost[now_vid] + 1 q.append((dim, ne_row, ne_col)) elif A[dim][ne_row][ne_col] == "G": print(vid_cost[now_vid] + 1) exit() elif 11<= A[dim][ne_row][ne_col]: ne_dim = A[dim][ne_row][ne_col] - 10 ne_vid = ne_dim*H*W + W*ne_row + ne_col if vid_cost[ne_vid] == None: vid_cost[ne_vid] = vid_cost[now_vid] + 1 q.append((ne_dim, ne_row, ne_col)) elif 1<= A[dim][ne_row][ne_col]: if dim == A[dim][ne_row][ne_col]: ne_vid = dim*H*W + W*ne_row + ne_col if vid_cost[ne_vid] == None: vid_cost[ne_vid] = vid_cost[now_vid] + 1 q.append((dim, ne_row, ne_col)) print(-1)