#ARGUMENTS
#f: 2-d array that describes the field
#sy, sx: starting point
#h, w: height and width fo the field

$dx = [0,1,0,-1]
$dy = [1,0,-1,0]
def bfs(f, sy, sx, h, w, n, cur)
    steps = Array.new(h).map{Array.new(w,-1)}
    steps[sy][sx] = 0
    q = [[sy,sx]]
    visited = Array.new(h).map{Array.new(w)}
    visited[sy][sx] = true
    while q.size > 0
        sy, sx = q.shift
        for i in 0..3
            cy = sy + $dy[i]
            cx = sx + $dx[i]
            if cy.between?(0,h-1) && cx.between?(0,w-1) && !visited[cy][cx] && f[cy][cx]!= "X"
                q.push([cy,cx])
                visited[cy][cx] = true
                if cur == f[cy][cx].to_i
                    return [steps[sy][sx] + 1, cy, cx]
                end
                steps[cy][cx] = steps[sy][sx] + 1
            end
        end
    end
end

h, w, n = gets.split.map(&:to_i)
f = h.times.map{gets.chomp}
sy = sx = 0
f.each_with_index do |r,i|
    if r.include?("S")
        sy = i
        sx = r.index("S")
    end
end
ret = 0
1.upto(n) do |i|
    a = bfs(f, sy, sx, h, w, n, i)
    ret += a[0]
    sy = a[1]
    sx = a[2]
end
puts ret