# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0558

"""
import sys
from sys import stdin
from collections import deque
input = stdin.readline


def bfs(field, sx, sy, gx, gy):
    # ????????????????§????????????´????????§?¨??????????
    dy = [-1, 1, 0, 0]
    dx = [0, 0, -1, 1]

    # ??°???????????????(?§????????????£????????????????????????????????§??????????????¨)
    Y = len(field)
    X = len(field[0])
    d = [[float('inf')] * X for _ in range(Y)] #  ??????????????°?????????????????¢???INF??§?????????

    # ??°???????????????(?§????????????£????????????????????????????????§??????????????¨)
    Y = len(field)
    X = len(field[0])

    Q = deque()
    Q.append((sx, sy))
    d[sy][sx] = 0               #  ??????????????°??????????????????0
    while Q:
        cx, cy = Q.popleft()        #  ?????¨??°?????§?¨?
        if cx == gx and cy == gy:
            break
        for i in range(4):
            nx = cx + dx[i]
            ny = cy + dy[i]
            # ?§?????????? ??°????????????????????????????????? and ?£?????????£???????????? and ??¢?????¢?´¢?????§?????? ??´???
            if (0 <= nx < X) and (0 <= ny < Y) and field[ny][nx] != 'X' and d[ny][nx] == float('inf'):
                Q.append((nx, ny))
                d[ny][nx] = d[cy][cx] + 1
    return d[gy][gx]


def find_mark(data):
    founds = []
    if 'S' in data:
        founds.append(['S', data.index('S')])
    if '1' in data:
        founds.append(['1', data.index('1')])
    if '2' in data:
        founds.append(['2', data.index('2')])
    if '3' in data:
        founds.append(['3', data.index('3')])
    if '4' in data:
        founds.append(['4', data.index('4')])
    if '5' in data:
        founds.append(['5', data.index('5')])
    if '6' in data:
        founds.append(['6', data.index('6')])
    if '7' in data:
        founds.append(['7', data.index('7')])
    if '8' in data:
        founds.append(['8', data.index('8')])
    if '9' in data:
        founds.append(['9', data.index('9')])
    return founds

def solve(field, N):
    # ??????????????°???(S)??¨??´????????°???(G)?????????
    pos = [[None, None] for _ in range(N+1)]
    for y, row in enumerate(field):
        res = find_mark(row)
        for mark, x in res:
            if mark is not None:
                if mark == 'S':
                    pos[0] = [x, y]
                else:
                    pos[int(mark)] = [x, y]

    total_move = 0
    start = pos[0]
    for goal in pos[1:]:
        sx, sy = start
        gx, gy = goal
        res = bfs(field, sx, sy, gx, gy)
        # print('From: ({}, {}) -> To: ({}, {}), step: {}'.format(sx, sy, gx, gy, res))
        # print('min move: {}'.format(abs(sx-gx) + abs(sy-gy)))
        total_move += res
        start = goal

    return total_move


def main(args):
    # N = 9
    # data = [
    #     '.X...X.S.X',
    #     '6..5X..X1X',
    #     '...XXXX..X',
    #     'X..9X...X.',
    #     '8.X2X..X3X',
    #     '...XX.X4..',
    #     'XX....7X..',
    #     'X..X..XX..',
    #     'X...X.XX..',
    #     '..X.......'
    # ]
    H, W, N = map(int, input().split())
    data = [input().strip('\n') for _ in range(H)]
    field = [list(x) for x in data] #  data????????????????????????????????????????????????
    result = solve(field, N)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Measured memory_bytes: 38472