require "set"

m, n, k = gets.split.map(&:to_i)

a = (1..m).map { [?X] + gets.chomp.split("") + [?X] }
a << [?X] * (n+2)
a.unshift([?X] * (n+2))

points = []
(1..m).each{|i|
	(1..n).each{|j|
		case a[i][j]
		when ?S
			points[0] = [i,j]
		when /\d/
			points[a[i][j].to_i] = [i,j]
		end
	}
}

total_dist = 0

points.each_cons(2){|s, t|
	reached = Set[s]
	dist = 0
	queue = [s]
	found = false
	loop {
		next_queue = []
		until queue.empty?
			u = queue.shift
			if u == t
				found = true
				break
			end
			i, j = u
			[[1,0],[-1,0],[0,1],[0,-1]].each{|dx, dy|
				y, x = i+dy, j+dx
				v = [y, x]
				if a[y][x] != ?X && !reached.include?(v)
					reached << v
					next_queue << v
				end
			}
		end	
		break if found
		queue = next_queue
		dist += 1
	}
	total_dist += dist
}
p total_dist