import util.control.Breaks._

object Main extends App {
  val Array(h,w,n) = io.StdIn.readLine().split(' ').map(_.toInt)
  val field = Array.fill(h)(io.StdIn.readLine().toCharArray)
  var start = (0,0)
  breakable {for (j <- 0 until h; i <- 0 until w; if field(j)(i) == 'S') start = (j, i); break}
  val costs = for (g <- 1 to n) yield {
    val heap = collection.mutable.PriorityQueue.empty[((Int, Int), Int)](Ordering.by(-_._2))
    heap.enqueue((start, 0))
    val taken = Array.fill(h)(Array.fill(w)(Int.MaxValue))
    @scala.annotation.tailrec
    def loop(): Int = heap.dequeue() match {
      case ((y, x), cost) if field(y)(x) == (g+48).toChar => start = (y, x); cost
      case ((y, x), cost) =>
        val nextCost = cost + 1
        Seq((y,x-1),(y,x+1),(y-1,x),(y+1,x))
          .withFilter(p => p._1 >= 0 && p._1 < h && p._2 >= 0 && p._2 < w)
          .withFilter(p => (field(p._1)(p._2) != 'X') && nextCost < taken(p._1)(p._2))
          .foreach{p => taken(p._1)(p._2) = nextCost; heap.enqueue((p, nextCost))}
        loop()
    }
    loop()
  }
  println(costs.sum)
}
