
require 'pp'

def is_i?(string)
  string =~ /^[0-9]+$/
end
class Array
  def product
    self.inject(1) {|sum, elem| sum * elem}
  end
  def sum
    self.inject(0) {|sum, elem| sum + elem}
  end
end

h, w, n = $stdin.gets.chomp.split(" ").map(&:to_i)
cheese_map = h.times.map {[nil] + $stdin.gets.chomp.bytes.to_a.map(&:chr) + [nil]}
cheese_map.insert(h, Array.new(w + 2, nil))
cheese_map.insert(0, Array.new(w + 2, nil))

def bfs_search(map, start)
  directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
  queue = []
  map[start[:i]][start[:j]] = nil
  goal = start[:item] - 1
  queue.push({:pos => [start[:i], start[:j]], :counter => 0})
  until queue.empty? do
    item = queue.shift
    directions.each do |(i, j)|
      ny = item[:pos][0] + i
      nx = item[:pos][1] + j
      next_item = map[ny][nx]
      if (next_item == goal) then
        return item[:counter] + 1
      elsif (next_item == "." or next_item.is_a?(Numeric)) then
        queue.push({:pos => [ny, nx], :counter => item[:counter] + 1})
        map[ny][nx] = nil
      else next end
    end
  end
end

def deep_copy(object)
  Marshal.load(Marshal.dump(object))
end

cheeses = []

cheese_map.each_with_index do |line, i|
  line.each_with_index do |item, j|
    if is_i?(item) then
      cheeses << {:i => i, :j => j, :item => item.to_i}
      cheese_map[i][j] = item.to_i
    elsif (item == "S") then
      cheese_map[i][j] = 0
    end
  end
end

cheeses = cheeses.sort_by {|elem| elem[:item]}
result = cheeses.map do |cheese|
  bfs_search(deep_copy(cheese_map), cheese)
end.sum

puts result