def bfs(n)
  si, sj = $pos[n - 1]
  gi, gj = $pos[n]

  secs = {"#{si},#{sj}" => 0}
  q = [[si, sj]]

  mv = [[0, 1], [0, -1], [1, 0], [-1, 0]]
  while pos = q.shift
    ci, cj = pos
    return secs["#{ci},#{cj}"] if ci == gi && cj == gj

    mv.each do |mi, mj|
      ni = ci + mi
      next if ni < 0 || ni >= $h
      nj = cj + mj
      next if nj < 0 || nj >= $w

      next if secs["#{ni},#{nj}"] || $map[ni][nj] == 'X'

      secs["#{ni},#{nj}"] = secs["#{ci},#{cj}"] + 1
      q.push [ni, nj]
    end
  end
end

$h, $w, $n = gets.split(' ').map(&:to_i)

$map = []
$pos = {}
0.upto($h - 1) do |i|
  $map[i] = gets.chomp.split(//)
  0.upto($w - 1) do |j|
    case $map[i][j]
    when 'S'
      $pos[0] = [i, j]
    when 'X', '.'
    else
      $pos[$map[i][j].to_i] = [i, j]
    end
  end
end

ans = 0
1.upto($n) do |n|
  ans += bfs(n)
end
puts ans