### constant

MAX_INT = 1 << 30
DRCS = [[1, 0], [0, -1], [-1, 0], [0, 1]]

### main

h, w, n = gets.strip.split(' ').map{|s| s.to_i}

brd = (h + 2).times.map{(w + 2).times.map{0}}
(0..(h + 1)).each{|y| brd[y][0] = brd[y][w + 1] = -1}
(0..(w + 1)).each{|x| brd[0][x] = brd[h + 1][x] = -1}

start = nil
dests = []

for y in (1..h)
  hl = gets.strip
  for x in (1..w)
    case hl[x - 1]
    when 'S'
      start = [y, x]
    when 'X'
      brd[y][x] = -1
    when '1'..'9'
      dests[hl[x - 1].to_i - 1] = [y, x]
    end
  end
end
#p brd
#p start
#p dests

total = 0

for dest in dests
  dists = (h + 2).times.map{(w + 2).times.map{MAX_INT}}
  dists[start[0]][start[1]] = 0

  q = [start]

  while ! q.empty?
    u = q.min{|a, b| dists[a[0]][a[1]] <=> dists[b[0]][b[1]]}
    q.delete u

    y, x = u
    du = dists[y][x]

    break if u == dest

    for drc in DRCS
      y0 = y + drc[0]
      x0 = x + drc[1]

      if brd[y0][x0] != -1
        dv = dists[y0][x0]
        if dv > du + 1
          dists[y0][x0] = du + 1
          q << [y0, x0] if dv >= MAX_INT
        end
      end
    end
  end

  total += du
  start = dest
end

puts total