module Graph
	require 'set'
	def add_node(label = nil)
		Node.new(label)
	end

	def add_edge(u, v, label = nil)
		e = Edge.new(u, v, label)
		u.outgoings << e
		v.incomings << e
		e
	end
	
	def del_edge(e)
		u, v = e.from, e.to
		u.outgoings.delete(e)
		v.incomings.delete(e)
		e
	end

	class Node
		def initialize(label)
			@label = label
			@outgoings = Set.new
			@incomings = Set.new
		end

		def to_nodes
			@outgoings.map(&:to)
		end

		def from_nodes
			@incomings.map(&:from)
		end

		def to_s
			@label
		end
		
		attr_accessor :incomings, :outgoings
		attr_reader :label
	end

	class Edge
		def initialize(u, v, label = nil)
			@from = u	
			@to = v
			@label = label
		end
		attr_reader :from, :to, :label
	end

	def get_path_bfs(s, t)
		path_edge = {}
		reached = Set[s]
		queue = [s]
		while !queue.empty? 
			u = queue.shift
			u.outgoings.each{|e|
				v = e.to
				next if reached.include?(v)	
				reached << v
				queue << v
				path_edge[v] = e

				if v == t
					path = []
					while e = path_edge[v]
						path.unshift e
						v = e.from
					end
					return path
				end
			}
		end	
		return nil
	end

	def get_path_dfs(s, t, reached = Set.new)
		reached << s	
		s.outgoings.each{|e|
			v = e.to
			next if reached.include?(v)
			return [e] if v == t
			
			path = get_path_dfs(v, t, reached) 
			return [e] + path if path
		}
		nil
	end

	def layers_from(start)
		reached = Set[*start]
		layers = [start]

		loop {
			layers << []
			layers[-2].each{|u|
				u.to_nodes.each{|v|
					next if reached.include?(v)
					reached << v
					layers[-1] << v
				}
			}	

			if layers[-1].empty?
				layers.pop
				return layers
			end
		}
	end

	def reachable_from(s, reached = Set.new, root = true)
		reached << s	
		s.outgoings.each{|e|
			v = e.to
			next if reached.include?(v)
			reachable_from(v, reached, false) 
		}
		root ? reached : nil
	end

	def dijkstra(s)
		dist = {}
		h = Heap.new
		h.add(s, 0)
		reached = Set[s]
		until h.size == 0
			u, key = h.del_min
			dist[u] = key
			u.outgoings.each{|e|
				v = e.to
				d = dist[u] + e.label
				if reached.include?(v)
					h.update_key(v, d)
				else
					h.add(v, d)
					reached << v
				end
			}
		end
		dist
	end
end

include Graph

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

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

nodes = {}
(0..m-1).each{|i|
	(0..n-1).each{|j|
		next if a[i][j] == ?X
		nodes[[i, j]] = add_node
	}
}

points = []
(0..m-1).each{|i|
	(0..n-1).each{|j|
		u = nodes[[i, j]]
		case a[i][j]
		when ?X
			next
		when ?S
			points[0] = nodes[[i,j]]
		when /\d/
			points[a[i][j].to_i] = nodes[[i,j]]
		end
		
		if a[i+1][j] != ?X
			v = nodes[[i+1,j]]
			add_edge(u, v)
			add_edge(v, u)
		end
		if a[i][j+1] != ?X
			v = nodes[[i,j+1]]
			add_edge(u, v)
			add_edge(v, u)
		end
	}
}

dist = 0
points.each_cons(2){|s, t|
	dist += get_path_bfs(s, t).size
}
p dist